shell脚本,结合expect给当前网段所有主机分发任意文件

124 阅读1分钟

1.安装expect yum -y install expect

2.root目录下创建iplist.txt文件(要分发的IP地址) 192.168.100.129 192.168.100.130

3.root目录下创建user.txt(是服务器的密码) 123456 123456 4.创建脚本 test.sh,test.log(脚本后面不可以有注释的)

#!/bin/bash
echo "拷贝情况如下:" > /root/test.log
n=`cat /root/iplist.txt | wc -l` #分发的ip数量
for (( i=1; i<=$n; i++ ))
do
	passwd=`cat /root/user.txt|head -$i|tail -1`#第i个IP地址的密码

    ip=`cat /root/iplist.txt|head -$i|tail -1`#第i个IP地址
    echo $ip
##自动交互
/usr/bin/expect <<EOF
spawn scp /root/1.txt $ip:/root/
expect "yes/no" {send "yes\n;exp_untinue"}
expect "password" {send "$passwd\n"}
expect eof
EOF
if [ $? -eq 0 ];then
   echo "$ip:成功" >>/root/test.log
else
   echo "$ip:失败" >>/root/test.log
fi        
done