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:

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

Three files needed:
file ip-list.txt

192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5

file sshauto.sh

#!/bin/bash
echo -n "Password:"
read -s passw; echo
stty echo
command=$2
while read IP
do
    ./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