Skip to content

Instantly share code, notes, and snippets.

@ultimate010
Created August 12, 2015 08:58
Show Gist options
  • Save ultimate010/cd61524b18aecffdafbd to your computer and use it in GitHub Desktop.
Save ultimate010/cd61524b18aecffdafbd to your computer and use it in GitHub Desktop.
#!/usr/bin/expect -f
set timeout -1
if { ${argc} < 2 } {
send_user "Usage:\n"
send_user "\t${argv0} PASSWORD \[USER@\]HOST \[COMMAND1 \[; COMMAND2\] ...\]\n"
send_user "\n"
send_user "Default USER is current login\n"
send_user "Without any COMMAND, will get an interactive shell on the remote.\n"
send_user "With COMMAND(s), it will be run on the remote, and return the last command's status.\n"
send_user "multi-COMMANDs with semicolon delimited must be quoted.\n"
send_user "Any failure for this script, will exit with non-zero value.\n"
send_user "\n"
send_user "e.g:\n"
send_user "\t${argv0} password 172.16.34.2\n"
send_user "\t${argv0} password root@172.16.34.2\n"
send_user "\t${argv0} password root@172.16.34.2 touch /tmp/file1 /tmp/file2\n"
send_user "\t${argv0} password root@172.16.34.2 'touch /tmp/file1 /tmp/file2; ls /tmp/file*;'\n"
send_user "\n"
exit 1
}
set password [lindex ${argv} 0]
set host [lindex ${argv} 1]
set cmd [lrange ${argv} 2 end]
set cmd_str ""
set cmd_llen [llength ${cmd}]
for { set i 0 } { ${i} < ${cmd_llen} } { incr i } {
# remove curly braces generated by TCL List
set item [lindex ${cmd} ${i}]
set item_llen [llength ${item}]
if { ${cmd_llen} == 1 } { # <cmd> has only 1 element
append cmd_str ${item}
} elseif { ${item_llen} == 0 || ${item_llen} > 1 } { # <item> has zero or more than 1 elements
append cmd_str "\"${item}\""
} else { # <item> has only 1 element
append cmd_str ${item}
}
if { [expr ${cmd_llen} - ${i}] > 1 } {
append cmd_str " "
}
}
spawn -noecho ssh -o "StrictHostKeyChecking no" ${host} ${cmd_str}
expect {
eof { exit [lindex [exp_wait] 3] }
"\> $" { interact }
"\# $" { interact }
"\$ $" { interact }
"(yes/no)? $" {
send "yes\n"
exp_continue
}
" ?assword: $" {
send "${password}\n"
expect {
eof { exit [lindex [exp_wait] 3] }
"\> $" { interact }
"\# $" { interact }
"\$ $" { interact }
" ?assword: $" {
send_user "\n${argv0}: login failed! wrong password!\n"
exit 1
}
default {
send_user "\n${argv0}: login failed!\n"
exit 1
}
}
}
default {
send_user "\n${argv0}: connection failed!\n"
exit 1
}
}
exit [lindex [exp_wait] 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment