判断主机是否在线

判断主机是否在线

我正在测试机器的稳定性,我需要简单地编写 Bash 脚本来确定主机是否在线的方法。我该如何编写这个脚本?

if [ ! $(hostisonline) ]; then
    # profit
fi

答案1

如果主机应答 ping,则测试其是否在线(仅作为示例):

ping -c 10 $host

如果 ping 未返回/被禁止,我将通过 nmap 检查各个服务:

nmap $host -p $known_port --max-retries 10 | grep -q open

例如,要测试是否需要打开 ssh,请将known_port替换为22

至于脚本,它可能是(示例 - 这是周日早上,我很无聊,所以经过一些编辑后它已经增长了一点 - 旨在测试一堆主机,而不仅仅是一个):

declare -A SERVER
# SERVER["NAME - Description"]="IP KNOWNPORT"
SERVER["SERVER1 - Client foo"]="111.111.111.111 22"
SERVER["SERVER2 - Client bar"]="222.222.222.222 80"
# ...
# add as many server/port combinations as you'd like

NMAP_MAX_RETRIES=10

printf "========================= ========================= ========== ==========\n"
printf "%25s %25s %10s %10s\n" "Host Description" "IP" "Port" "Status"
printf "========================= ========================= ========== ==========\n"


for server in "${!SERVER[@]}"; do
    set -- ${SERVER["$server"]}
    eval nmap \$1 -p \$2 --max-retries $NMAP_MAX_RETRIES | grep -q open
    if [ "$?" == "0" ]; then
        STATUS="[OK]"
    else
        STATUS="*DOWN*" 
    fi
    printf "%25s %25s %10s %10s\n" "$server" "$1" "$2" "$STATUS" 
done

 printf "========================= ========================= ========== ==========\n"

执行时会返回(假 IP,因此服务器已关闭):

 ~$ bash /tmp/foo.sh
 ========================= ========================= ========== ==========
          Host Description                        IP       Port     Status
 ========================= ========================= ========== ==========
      SERVER2 - Client bar           222.222.222.222         80     *DOWN*
      SERVER1 - Client foo           111.111.111.111         22     *DOWN*
 ========================= ========================= ========== ==========

答案2

一个简单的解决方案是:

ping -W 1 $ip

其中-W指定超时(以秒为单位)。

确保它是大写的 W。您还可以用来-i指定等待时间(以秒为单位)。

相关内容