Shell批量复制或运行文件
全部脚本放在同一个目录下:
1 根据ip密码文件,批量处理
passwd.txt 格式
-
192.168.9.111 password
-
192.168.9.112 password
-
192.168.9.113 password
-
192.168.9.114 password
2 登录脚本login.exp
-
#!/usr/bin/expect -f
-
set ip [lindex $argv 0 ]
-
set passwd [lindex $argv 1 ]
-
set command [lindex $argv 2]
-
set timeout -1
-
spawn ssh root@$ip
-
expect {
-
\"yes/no\" { send \"yes\\r\";exp_continue }
-
\"password:\" { send \"$passwd\\r\" }
-
}
-
expect \"*#*\" { send \"$command\\r\" }
-
expect \"#*\" { send \"exit\\r\" }
-
expect eof
3 批量复制文件scp.sh
[root@ passwdsh]# sh scp.sh filename
-
uto exec expect shell scripts
-
if
-
[ ! -e /usr/bin/expect ];then
-
yum install expect -y
-
fi
-
#Judge passwd.txt exist
-
if
-
[ ! -e ./passwd.txt ];then
-
echo -e \"The passwd.txt is not exist......Please touch ./passwd.txt ,Content Example:\\n192.168.1.11 passwd1\\n192.168.1.12 passwd2\"
-
sleep 2 &&exit 0
-
fi
-
#Auto Tuoch login.exp File
-
cat>login.exp <<EOF
-
#!/usr/bin/expect -f
-
set ip [lindex \\$argv 0]
-
set passwd [lindex \\$argv 1]
-
set src_file [lindex \\$argv 2]
-
set des_dir [lindex \\$argv 3]
-
set timeout -1
-
spawn scp -p \\$src_file root@\\$ip:\\$des_dir
-
expect {
-
\"yes/no\" { send \"yes\\r\"; exp_continue }
-
\"password:\" { send \"\\$passwd\\r\" }
-
}
-
expect \"100%\"
-
expect eof
-
EOF
-
##Auto exec shell scripts
-
if
-
[ \"$1\" == \"\" ];then
-
echo ========================================================
-
echo \"Please insert your are command ,Example {/bin/sh $0 /src /des } ,waiting exit ........... \"
-
sleep 2
-
exit 1
-
fi
-
for i in `awk \'{print $1}\' passwd.txt`
-
do
-
j=`awk -v I=\"$i\" \'{if(I==$1)print $2}\' passwd.txt`
-
expect ./login.exp $i $j $1 $2
-
done
4 批量运行脚本ssh.sh
[root@ passwdsh]# sh ssh.sh filename
-
uto exec expect shell scripts
-
if
-
[ ! -e /usr/bin/expect ];then
-
yum install expect -y
-
fi
-
#Judge passwd.txt exist
-
if
-
[ ! -e ./passwd.txt ];then
-
echo -e \"The passwd.txt is not exist......Please touch ./passwd.txt ,Content Example:\\n192.168.1.11 passwd1\\n192.168.1.12 passwd2\"
-
sleep 2 &&exit 0
-
fi
-
#Auto Tuoch login.exp File
-
cat>login.exp <<EOF
-
#!/usr/bin/expect -f
-
set ip [lindex \\$argv 0 ]
-
set passwd [lindex \\$argv 1 ]
-
set command [lindex \\$argv 2]
-
set timeout -1
-
spawn ssh root@\\$ip
-
expect {
-
\"yes/no\" { send \"yes\\r\";exp_continue }
-
\"password:\" { send \"\\$passwd\\r\" }
-
}
-
expect \"*#*\" { send \"\\$command\\r\" }
-
expect \"#*\" { send \"exit\\r\" }
-
expect eof
-
EOF
-
##Auto exec shell scripts
-
CMD=\"$*\"
-
if
-
[ \"$1\" == \"\" ];then
-
echo ========================================================
-
echo \"Please insert your command ,Example {/bin/sh $0 \'mkdir -p /tmp\'} ,waiting exit ........... \"
-
sleep 2
-
exit 1
-
fi
-
for i in `awk \'{print $1}\' passwd.txt`
-
do
-
j=`awk -v I=\"$i\" \'{if(I==$1)print $2}\' passwd.txt`
-
expect ./login.exp $i $j \"$CMD\"
-
done
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29500582/viewspace-1284955/
,如需转载,请注明出处,否则将追究法律责任。