2007/09/14

Simple expect ssh example

This expect script would be called from a shell script, and would ssh to the host passed as an argument (argv), perform the command specified, and disconnect. (Thanks, Tiger O.)

#!/usr/bin/expect

set timeout 1
set cmd {uname -a}

spawn ssh root@$argv
expect_after eof { exit 0 }


## interact with SSH
expect "yes/no" { send "yes\r" }
expect "password:" { send "rootpasswd\r" }

expect "# "
send "$cmd\r"
expect "$cmd\r"
expect "(.*)\r"
send "exit\r

5 comments:

Unknown said...

This is very usefull ...
if i only could pass commands to this script

Anonymous said...

Thanks Sir. It is working fine.

-One of Unix fellow

Anonymous said...

send "exit\r need " in the end of the line

Lane said...

@cristian -- I know. But, you can always use a wrapper script in bash, possibly calling expect within a loop, to pass in any desired commands.

I've not looked lately, but surely there are some more flexible alternatives to expect... I'm thinking that this could be done easily enough with python....

Anonymous said...

@cristian: Expect already supports command line parameters, see here:

http://stackoverflow.com/questions/17059682/how-to-pass-argument-in-expect-through-command-line-in-shell-script