首页 > 解决方案 > ping 脚本 - 主机关闭与主机不在网络上

问题描述

我有以下脚本,我试图区分已关闭的服务器和不再在网络上的服务器。如果我在刚刚关闭的服务器的命令行上使用 ping 命令并回显 $? 我得到了预期的 1 。如果我在不再位于网络上的服务器的命令行上使用 ping 命令并回显 $? 我得到了预期的2。我似乎无法在我的脚本中捕捉到这种行为。在下面的脚本中,不再在网络上的服务器根本不会出现在 badhosts 输出文件中。我在 ping 行上使用 dev null,因为我不想在输出上获取主机未知行,这会扭曲结果。

提前感谢您的任何帮助。

#!/bin/ksh
# Take a list of hostnames and ping them; write any failures
#set -x

for x in `cat hosts`
do
ping -q -c 1 $x > /dev/null 2> /dev/null

if [ "$?" -eq 1 ];then
        echo $x is on network but down >> badhosts
elif [ "$?" -eq 2 ];then
        echo $x is not on the network >> badhosts
  fi
done

标签: shellkshping

解决方案


我根据拉曼的建议修改了我的脚本,如下所示,这很有效。谢谢拉曼!!

#!/bin/ksh
# Take a list of hostnames and ping them; write any failures
set -x

for x in `cat hosts`
do
ping -c 1 $x > /dev/null 2> /dev/null
pingerr=$?

if [ $pingerr -eq 1 ]; then
        echo $x is on network but down >> badhosts
fi

if [ $pingerr -eq 2 ]; then
        echo $x is not on the network >> badhosts
fi
done

推荐阅读