许多人问了批量怎么修改linux服务器密码等问题,主要是解决ssh登陆交互的问题,除了做key等办法外,还有就是利用expect来解决,大多数情况,需要批量在服务器上相同操作的时候,都可以借用此脚本 ,所以我在此也记录下我找资料调试后的脚本,方便使用.
例如:批量在服务器上新建一个目录,"mkdir -p /root/new_directory".
expect的脚本如下(此脚本作用在于解决交互问题,并且执行所需操作):
#!/usr/bin/expect
#Filename: mkdir_expect
set loginuser "root"
set loginpass "feifei"
set ipaddr [ lrange $argv 0 0]
set timeout 300
set cmd_prompt "]#|~]?"
spawn ssh $loginuser@$ipaddr
set timeout 300
expect {
-re "Are you sure you want to continue connecting (yes/no)?" {
send "yes\r"
} -re "password:" {
send "$loginpass\r"
} -re "Permission denied,please try again." {
exit
} -re "Connection refused" {
exit
} timeout {
exit
} eof {
exit
}
}
expect {
-re "password:" {
send "$loginpass\r"
}
-re $cmd_prompt {
send "\r"
}
}
#sleep 1
expect "#"
send "mkdir -p /root/new_directory\r"
expect -re $cmd_prompt
exit
##################################################################
下面是shell脚本,简单调用expect.
#!/bin/bash
EXPECT="/usr/bin/expect"
MK_EXPECT="/root/shellscripts/mkdir_expect"
for ip in `cat /root/shellscripts/ip_list | awk '{print $2}'`;do
ping -c 1 "$ip" > /dev/null 2>&1
if [ $? -eq 0 ];then
"$EXPECT" "$MK_EXPECT" "$ip"
echo "$ip" is ok! > log/run.log
else
echo "$ip" is death! > log/run.log
fi
done
转载于:https://blog.51cto.com/wanghaipeng1124/839740