此脚本需要expect命令,使用前确认一下机器收否有安装:which expect
思路:1.编写好要追加到hosts文件内容的文件(IP_hosts_test)
2.编写脚本文件testRead.sh(嵌套expect,实现自动登录),读取上面的文件,获取ip,然后登录到其他机器,追加hosts
#!/bin/bash
ips=`cat IP_hosts_test |awk '{print $1}'`
for ip in $ips
do
echo -e "\n-------------开始追加hosts文件---------------------\n"
password='rootroot'
ip='127.0.0.1'
echo -e "\n\n$ip\n"
/usr/bin/expect<<EOF
spawn scp /tmp/IP_hosts_test [email protected]$ip:/tmp/
expect {
"(yes/no)?" {
send "yes\r"
expect "*assword" {
send "$password\r"
}
}
"*assword" {
send "$password\r"
}
}
spawn ssh $ip
expect {
"(yes/no)?" {
send "yes\r"
expect "*assword" {
send "$password\r"
}
}
"*assword" {
send "$password\r"
}
}
expect "*]#"
send "cat /tmp/IP_hosts_test >> /etc/hosts\r"
expect eof
EOF
echo -e "\n-------------追加hosts文件结束---------------------\n"
done