Bash - auto SSH with expect and sudo commands

Posted on Fri 01 January 2010 by Pavlo Khmel

Example with auto creating user on several servers:

./ ip-list.txt 'hostname; sudo useradd -m -c "PHN user2" -G phn phnname2 -p $1$PvdTXX8sX$rTuP4VtQ'

Three files needed:
file ip-list.txt


echo -n "Password:"
read -s passw; echo
stty echo
while read IP
    ./sshlogin.exp $passw $IP "$command"
done < $1

file sshlogin.exp

#!/usr/bin/expect -f
set password [lrange $argv 0 0]
set ipaddr [lrange $argv 1 1]
set scriptname [lindex $argv 2]
set arg1 [lrange $argv 3 3]
set timeout -1
spawn ssh -t -o stricthostkeychecking=no phnuser1@$ipaddr $scriptname $arg1
match_max 100000
expect "*?assword:*"
send -- "$passwordr"
expect "*?assword:*"
send -- "$passwordr"
send -- "r"
expect eof