Posted to tcl by rahl at Wed Nov 16 10:46:42 GMT 2022view raw

  1. #!/bin/expect -f
  2.  
  3. # Send SIGINT and exit
  4. proc abort {code} {
  5. # TODO: Is the SIGINT really necessary?
  6. # Equivalent to Ctrl-C
  7. send \x03
  8. exit $code
  9. }
  10.  
  11. if {[llength $argv] < 3} {
  12. puts "Usage: autoborg.exp user passwd-file command [args]"
  13. exit 33
  14. }
  15.  
  16. set command [lassign $argv user passwd]
  17.  
  18. set fp [open "${passwd}" r]
  19. set data [split [read $fp] \n]
  20. close $fp
  21.  
  22. set pass_idx 0
  23.  
  24. spawn sudo -u $user {*}$command
  25.  
  26. # Handle ssh, sudo and doas passphrase/words
  27. set pass_request [join [list {*}{
  28. "Enter passphrase for key '.*': "
  29. "\[sudo\] password for .*: "
  30. "doas \(.*\) password: "
  31. }] |]
  32.  
  33. expect {
  34. -re $pass_request {
  35. if {$pass_idx >= [llength $data]} {
  36. abort 34
  37. }
  38.  
  39. set server_pass [lindex $data $pass_idx]
  40. send "${server_pass}\r"
  41.  
  42. incr pass_idx
  43. exp_continue
  44. }
  45.  
  46. "Authentication failed" {
  47. abort 35
  48. }
  49.  
  50. timeout { abort 36 }
  51. eof
  52. }
  53.  
  54. lassign [wait] pid spawnid os_error_flag value
  55.  
  56. if {$os_error_flag == 0} {
  57. puts "exit status: $value"
  58. } else {
  59. puts "errno: $value"
  60. }
  61.  
  62. # - borg
  63. # 0: success
  64. # 1: warning
  65. # 2: error
  66. # 128+N: killed by signal N
  67. #
  68. # - sudo
  69. # pass through: success
  70. # 1: auth failure (maybe other)
  71. #
  72. # - doas
  73. # 0: success
  74. # >0: error passthrough
  75. #
  76. # - ssh
  77. # pass through: success
  78. # 255: error
  79. #
  80. # - autoborg (this script)
  81. # 33: error - incorrect arg count
  82. # 34: abort - not enough passphrases
  83. # 35: abort - authentication failure
  84. # 36: abort - timeout
  85. #
  86. exit $value