然后再写一个通用的可以批量远程执行命令的expect脚本:
[root@localhost ~]# vim cmd.expect
#!/usr/bin/expect
set user [lindex $argv 0] # 系统用户
set host [lindex $argv 1] # 服务器地址
set passwd [lindex $argv 2] # 密码
set cm [lindex $argv 3] # 需要执行的命令
spawn ssh $user@$host
set timeout -1 #没有timeout ; set timeout XX -- 设定具体的timeout时间(秒) 防止命令死机
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}expect "]#"
send "$cm\r"
expect "]#"
send "exit\r"
interact
[root@localhost ~]# chmod a+x cmd.expect
[root@localhost ~]# vim cmd.sh # 调用脚本
#!/bin/bash
user=$2 ## 参数2是用户名
password=$3 ## 参数3是密码
cm=$4 ## 参数4需要执行的命令
for ip in `cat $1` ## 参数1是存储ip列表的文件路径
do
./cmd.expect "$user" "$ip" "$password" "$cm"
done
# 使用这个脚本批量安装一些基础通用的工具
[root@localhost ~]# sh ./cmd.sh "/root/ipAll.txt" "root" "lri35krJF;ba" "yum -y install expect vim-enhanced epel-release libmcrypt-devel libmcrypt"