批量SSH/SCP循环脚本

编辑一个列表vi list内容如下
ip1 密码
ip2 密码

修改脚本中shell='需要执行的命令'(`请不要使用此脚本执行带符号的命令,涉及的字符转译比较麻烦`)
修改sshuser为ssh登录的用户
执行脚本则返回每台设备的结果

如果需要使用SCP功能,需要注释spawn ssh,并取消注释#spawn scp
此时需要编辑拷贝的文件spawn scp $ip:/root/1.sh /root/2.sh
此脚本可用于文件分发和文件收集(`需要注意文件重名或覆盖可能`)

#!/bin/sh
shell='free -m'
sshuser=root
total=$(cat list | wc -l)
curr=0
while read ip password
do
curr=$(($curr + 1))
echo "=====================================[$total,$curr]Begin to process $ip ...."
if [ "$ip" != "" ]; then
ping -c 1 $ip > /dev/null
ret=$?
if [ $ret -eq 1 ]; then
printf "%03d: %s\r\n" $iCount "ping $ip Failed!"
echo $ip >> failed.log
else
expect -c "set timeout 20
set passwderror 0
#spawn scp $ip:/root/1.sh /root/2.sh
spawn ssh -o ConnectTimeout=3 $sshuser@$ip \"$shell\"
expect {
\"*assword:*\" {
if { \$passwderror == 1 } {
puts \"passwd is error\"
exit 2
}
set timeout 1000
set passwderror 1
send \"$password\r\"
exp_continue
}
\"*es/no)?*\" {
send \"yes\r\"
exp_continue
}
timeout {
puts \"connect is timeout\"
exit 3
}
}"
fi
fi
done < list

posted @ 2020-09-21 09:42  LEAUS  阅读(680)  评论(0)    收藏  举报