主机交互脚本


#!/bin/bash
if [[ $# -ne 1 ]]; then
echo "parameter error, please input iplist file!"    #判断是否跟文件
exit 1
fi
ipListFile=$1
timetmp=`date +%Y%m%d`
user=ansbmk
passwd="Qwkh210926#EDC"
ececFiledir="/tmp"
## 传回结果文件
targetuser=root
targetIP=10.230.103.2
targetDir="/root/zhangq/20211104_safeScan/messagebackup"
targetpasswd="1qaz!QAZ2wsx3edc4rfv"


while read line      #循环
do
ipaddr=${line}

/usr/bin/expect<set timeout 2

spawn ssh -l ${user} $ipaddr   #定义远程连接串
expect {
"*yes/n*" {         #第一次连接需要认证yes
send "yes\r"
expect "*assword:"        
send "$passwd\r"
}
"*assword:" {              #非第一次连接
send "$passwd\r"
}
}
expect "*$*"         #最后一个字符为$
send "sudo su\r"        #以sodu用户连接
expect "*password for*"
send "${passwd}\r"
expect "*#*"
send "cd ${ececFiledir}\r"
expect "*#*"
send "zip -q message_${line}_${timetmp}.zip /var/log/messages*\r"
expect "*#*"
send "cd /tmp\r"
expect "*#*"
send "scp /tmp/message_${line}_${timetmp}.zip ${targetuser}@${targetIP}:${targetDir}\r"
expect {
"*yes/n*" {
send "yes\r"
expect "*assword:"
send "$targetpasswd\r"
}
"*assword:" {
send "$targetpasswd\r"
}
}
expect "*#*"
send "rm -f /tmp/message_*.zip\r"
expect "*#*"
send "exit\r"
expect "*#*"
EOF

done <${ipListFile}

相关