检查服务器是否启动

Check if server is up

我想写一个脚本来检查服务器是否启动,如果没有启动,则休眠 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

我建议您根本不需要对此有任何期望。在bash

function ping1 {
    command ping -c 1 -W 1 "" >/dev/null
}

function ping2 {
    if ! ping1 ""; then
        sleep 120
        ping1 ""
    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= host= sleep=
    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

我想出来了,以防其他人感兴趣。 \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 [=10=]3}
        }
        sleep 30
}
puts "about to exit now";
exit