Sunday, November 4, 2012

Expect, su, ssh and sudo

in my relentless quest to automate remote execution of scripts, at last a working example:

this is to execute the following commands run from host1:
ssh pvernet@host2
(enter automatically the pvernet password on host2)
sudo su - soa
(enter automatically the pvernet password on host2)
touch /home/soa/pippo.txt 2> /tmp/errors.txt
exit
exit


(at the end you should return to host1, that's why I have 2 exit)

this is the file tryagain.expect:

#!/usr/bin/expect
log_user 1
set timeout 5
set user "pvernet"
set host "host2"
set pass "mypassword"
spawn ssh -q ${user}@${host}
expect "assword"
send "$pass\r\n"
expect "${user}@"
send "sudo su - soa\r\n"
expect "assword"
send "$pass\r\n"
expect "soa@"
send "touch /home/soa/pippo.txt 2> /tmp/errors.txt\r\n"
expect "host2"
send "exit\r\n"
expect "host2"
send "exit\r\n"
interact



run this with:
expect -f tryagain.expect


PRICELESS TIP: add "exp_internal 1" to debug the Expect dialog with the controlled process.



No comments: