Skip to content
All Posts

Automating Logins with Expect

An Expect script pattern that accepts command-line options or defaults to automate password-based interactive SSH logins.

Expect is a program for responding to interactive sessions based on their output; Python has a related library called pexpect. This example automates a login by putting the username and password in the script instead of using authorized_keys. Uploading a key is not always practical.

I modified the script to prefer command-line arguments and fall back to default values. Save it somewhere, add alias mycommand='expect /yourpath' to ~/.profile, then reload the profile and run it with mycommand.

Remember that an Expect script uses Expect’s own syntax, not Bash syntax.

#!/usr/bin/expect
set timeout 10
set user [lindex $argv 0 ]
set passwd [lindex $argv 1 ]
set jump_machine_id [lindex $argv 2]
set addr 192.192.11.22
if {[llength $argv] == 0} {
set user default_username
set passwd default_passwd
set jump_machine_id 3
}
spawn ssh "$user@$addr"
expect {
timeout {
"Password" { send "$passwd\r"; exp_continue }
"server" { send "${jump_machine_id}\r"; }
}
}
interact

Important reference


Originally published on SegmentFault.