管理机上需要安装expect包
yum -y install expect
1.定义主机ip
[root@localhost ~]# cat ip.txt
192.168.1.12
192.168.1.13
2.定义脚本内容
[root@localhost ~]# cat script.sh
vmstat
3、shell嵌套expect脚本
[root@localhost ~]# cat command.sh
#!/bin/bash
passwd='12345678'
sc=$(cat script.sh)
cat ip.txt | while read line
do
/usr/bin/expect <<EOF
set timeout 30
spawn ssh root@$line
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$passwd\r" }
}
expect "]# "
send "$sc\r"
send "exit\r"
expect eof
EOF
#首先定义密码为passwd变量,把发送的命令定义为sc变量,然后用循环读ip地址定义为line变量。
done
exit 0