sshw (2185B)
1 #!/usr/bin/expect 2 set timeout -1 3 match_max 100000 4 5 } 6 7 if { $argc < 1 } { 8 send_user "No hostname provided\n" 9 send_user "Targets: [join [dict keys $hosts] ","]\n" 10 exit 1 11 } 12 13 set command "ssh" 14 for {set i 0} {$i < $argc} {incr i} { 15 set ssharg [lindex $argv $i] 16 switch -glob [lindex $argv $i] { 17 -h { 18 send_user "Targets: [join [dict keys $hosts] ","]\n" 19 exit 0 20 } 21 sftp { 22 lset command 0 sftp 23 } 24 -C - 25 -A - 26 -X - 27 -Y - 28 -M { 29 lappend command $ssharg 30 } 31 -R - 32 -D - 33 -L - 34 -J { 35 lappend command $ssharg [lindex $argv [expr {$i + 1}]] 36 incr i 37 } 38 39 default { 40 set host [lindex $argv $i] 41 if {[dict exists $hosts $host]} { 42 set host [dict get $hosts $host] 43 } 44 # TODO: conditionally add -M? 45 lappend command {*}$host 46 } 47 } 48 } 49 send_user "Connecting with $command\n" 50 51 # Define a subroutine to read password 52 proc read_password {} { 53 stty -echo 54 send_user "password: " 55 expect_user -re "(.*)\n" 56 stty echo 57 set pass "$expect_out(1,string)\r" 58 send_user "\n" 59 return $pass 60 } 61 62 # Read password from user 63 set pass [read_password] 64 65 # Define procedure to log in 66 proc login {pass command} { 67 # Variables written in procedures don't change globally, 68 # but spawn_id has to be global for expect to work. 69 global spawn_id 70 71 # Connect 72 eval spawn $command 73 74 expect { 75 # Change password as needed 76 -ex "New password: " { 77 send -- "$pass" 78 expect -exact "Retype new password: " 79 send -- "$pass" 80 expect eof 81 82 # SSH closes the connection, so log in again 83 login $pass $command 84 } 85 # Accept fingerprint as needed 86 -ex "Are you sure you want to continue connecting (yes/no/\[fingerprint\])? " { 87 send -- "yes\r" 88 exp_continue 89 } 90 # On a shell prompt, stop expecting 91 "\$ $" {} 92 # Catch all - we got something we didn't expect 93 default { 94 send_user "Got some unexpected output\n" 95 exit 1 96 } 97 } 98 } 99 100 # Log in 101 login $pass $command 102 103 # Elevate privileges 104 if { [lindex $command 0] == "ssh" } { 105 send -- "sudo su\n" 106 expect -re "password for \[^ \]+: " 107 send -- "$pass" 108 } 109 110 # Yield control 111 interact