Linux Expect command example


“Expect” command in Linux is a script suite that use to interact with other script or command

Example 1:

spawn ssh saneri@172.133.1.122 df -Th
expect "*pwd"
send "hello\n"
expect eof

Example 2:

#!/bin/bash
passwd='pwd111'
/usr/bin/expect <<-EOF
set time 300
spawn ssh saneri@172.133.1.122 df -Th
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$passwd\r" }
}
expect eof
EOF


Example 3 :

Run multiple commands:

#!/usr/bin/expect -f
set timeout 10
spawn sudo su - root
expect "*password*"
send "123456\r"
expect "#*"
send "ls\r"
expect "#*"
send "df -Th\r"
send "exit\r"
expect eof


generate ssh key , and distribute id_rsa and id_rsa.pub to other hosts

1.create host

[root@localhost script]# cat host 
192.168.1.10 root 123456
192.168.1.20 root 123456
192.168.1.30 root 123456
[root@localhost script]# ls
copykey.sh  hosts


2. write copykey.sh that create and distribute key

[root@localhost script]# vim copykey.sh
#!/bin/bash
if [ ! -f ~/.ssh/id_rsa ];then
 ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa
else
 echo "id_rsa has created ..."
fi
#distribute to other hosts
while read line
  do
    user=`echo $line | cut -d " " -f 2`
    ip=`echo $line | cut -d " " -f 1`
    passwd=`echo $line | cut -d " " -f 3`
    
    expect <<EOF
      set timeout 10
      spawn ssh-copy-id $user@$ip
      expect {
        "yes/no" { send "yes\n";exp_continue }
        "password" { send "$passwd\n" }
      }
     expect "password" { send "$passwd\n" }
EOF
  done <  hosts


Invoke “Expect” command from shell

#!/bin/bash 
ip=$1  
user=$2 
password=$3 
expect <<EOF  
    set timeout 10 
    spawn ssh $user@$ip 
    expect { 
        "yes/no" { send "yes\n";exp_continue } 
        "password" { send "$password\n" }
    } 
    expect "]#" { send "useradd test\n" } 
    expect "]#" { send "touch /tmp/test.txt\n" } 
    expect "]#" { send "exit\n" } expect eof 
 EOF  
 #./ssh5.sh 172.10.200.1 oracleuser 11111


Update expired password

#!/bin/bash
for i in `cat /root/soft/ip.txt`
do
    /usr/bin/expect << EOF
    spawn /usr/bin/ssh root@$i
    expect {
        "UNIX password" { send "HP@188\r" }
    }
    
    expect {
        "New password:" { send "hpws@999#\r" }
    }
   expect {
        "Retype new password:" { send "hpwsss@333#\r" }
    }
    expect "*]#"
    send "echo hpws@99|passwd --stdin root\r"
    expect "*]#"
    send "exit\r"
    expect eof
EOF
done