有时候我们在产品发布之前可能面临需要对大量的服务器做环境验证,比方说在上百台server上验证文件是否存在,查看某个端口是否打开。 而我们又对服务器有很少的控制权限时,linux expect 是个不错的选择。
由于对expect不是很熟,写的比较乱
#########validateServer.sh
#!/bin/sh
if [ "$1" = "" ] || [ "$2" = "" ]; then
echo "invalid parameters"
else
for server in `cat $1`; do
echo "---------->" $server
./validateServer.expect "ssh username\@$server" "$2" password
done
fi
#########validateServer.expect
#!/usr/local/bin/expect -f
if {$argc!=3} {
send_user "usage: validateServer.expect host command password\n"
send_user "\teg. validateServer.expect \"ssh user@host\" \"ls -l\" password\n"
send_user "\tCaution: command should be quoted.\n"
exit
}
set host [lindex $argv 0]
set command [lindex $argv 1]
set password [lindex $argv 2]
eval spawn $host
expect {
"Are you sure you want to continue connecting (yes/no)?" {
# First connect, no public key in ~/.ssh/known_hosts
send "yes\r"
expect "assword:"
send "$password\r"
}
"Enter passphrase for key " {
# Already has public key in ~/.ssh/known_hosts
send "$password\r"
}
"assword:" {
# Already has public key in ~/.ssh/known_hosts
send "$password\r"
}
"Permission denied, please try again." {
# Password not correct
exit
}
"Connection refused" {
exit
}
}
set timeout 2
expect "/ $"
send "$command\n"
expect {
"Escape character is '^]'." {
sleep 2
send -- "\x1d"; # This is the hex value for ^]
expect "telnet> "
send -- "q\r"
}
}
expect "/ $"
send "exit\n"
set timeout 30
expect {
timeout {
send_user "timeout...\n"
exit
}
eof {
send_user "exit....\n"
exit
}
}
exit 0
server列表
#### server_list.data thejtechs-1.com thejtechs-2.com thejtechs-3.com thejtechs-4.com
测试:
./validateServer.sh server_list.data "telnet www.thejtechs.com 80"参考: http://www.thejtechs.com/blogDetail/74/linux-auto-telnet-for-server-validation
本文介绍如何使用Linux Expect脚本来自动化验证大量服务器的状态,包括检查文件存在性与端口开放情况,特别适用于对服务器控制权限有限的场景。
3419

被折叠的 条评论
为什么被折叠?



