Sometimes we need to log in to remote machines in batches, and execute related commands after switching users. If the efficiency is too low to log in and execute one by one, you can consider using the expect script
code show as below:
#!/bin/bash
LANG=en
user="lv"
command1="touch a.txt"
command2="chmod 777 a.txt"
command3="cp a.txt b.txt"
for line in `cat ip.list`;do
ip=`echo $line |awk -F "," '{print $1}'`
common_passwd=`echo $line |awk -F "," '{print $2}'`
new_rootpasswd=`echo $line |awk -F "," '{print $3}'`
/usr/bin/expect << EOF
set time 30
spawn ssh $user@$ip
expect {
"yes/no" { send "yes\r";exp_continue}
"password:" { send "$common_passwd\r"}
}
expect "]*"
send "su -\r"
expect {
"Password:" { send "$new_rootpasswd\r"}
}
expect "]*"
send "$command1\r"
expect "]*"
send "$command2\r"
expect "]*"
send "$command3\r"
expect "]*"
send "exit\r"
EOF
done
The text content of ip.list is as follows:
192.168.245.129,zhou2,Lg2=0.301!@#,
192.168.245.130,zhou3,e=2.71828!@#,
脚本执行结果如下:
spawn ssh [email protected]
[email protected]'s password:
Last login: Sun Nov 1 15:24:34 2020 from zhou1
[lv@zhou2 ~]$ su -
Password:
Last login: Sun Nov 1 15:28:18 CST 2020 on pts/1
[root@zhou2 ~]# touch a.txt
[root@zhou2 ~]# chmod 777 a.txt
[root@zhou2 ~]# cp a.txt b.txt
[root@zhou2 ~]# spawn ssh [email protected]
[email protected]'s password:
Last login: Sun Nov 1 15:29:36 2020 from 192.168.245.1
[lv@zhou3 ~]$ su -
Password:
Last login: Sun Nov 1 15:29:50 CST 2020 on pts/0
[root@zhou3 ~]# touch a.txt
[root@zhou3 ~]# chmod 777 a.txt
[root@zhou3 ~]# cp a.txt b.txt
[root @ zhou3 ~] # [lv @ zhou1 ~] $