我想编写一个脚本来检查服务器是否已启动,如果没有,请暂停30秒并再次ping通。但我只希望它重复这个循环10分钟或20次。我需要使用它,因为我的其他脚本更新了机器和系统重新启动,所以我需要等待它再次返回。我不想设置一个巨大的睡眠时间,因为这只是效率低下。
我正在ping 0.0.0.0作为示例。
提前致谢!
#!/usr/bin/expect -f
set timeout 30
set max_try 20
set tries 0
spawn ping 0.0.0.0
expect {
"64 bytes from 0.0.0.0" puts "servers are up"
if [ $tries -eq $max_try ]; then
puts "Test machine taking too long to reboot"
exit
fi
timeout {incr tries;exp_continue}
}
puts "Going to exit now"
exit
答案 0 :(得分:2)
我建议你根本不需要这样做。在bash中
function ping1 {
command ping -c 1 -W 1 "$1" >/dev/null
}
function ping2 {
if ! ping1 "$1"; then
sleep 120
ping1 "$1"
fi
}
host="0.0.0.0"
if ping2 "$host"; then
echo "$host is up"
else
echo "$host is down"
fi
新要求
function ping_many {
local tries=$1 host=$2 sleep=$3
while (( tries-- > 0 )) && ! ping1 "$host"; do
sleep "$sleep"
done
return $(( ! (tries >= 0) )) # have to invert the boolean value to a success/fail value
}
ping_many 20 0.0.0.0 30
答案 1 :(得分:0)
我想出来,以防其他任何人感兴趣。 \ 003表示ctrl + c
#!/usr/bin/expect -f
set timeout 5
set max_try 20
for {set i 0} {$i < $max_try} {incr i 1} {
puts "loop $i"
spawn ping -c 2 -i 3 -W 1 0.0.0.0
expect {
"2 packets transmitted, 2 received" {puts "servers are up"; break}
timeout {send \003}
}
sleep 30
}
puts "about to exit now";
exit