【问题标题】:ping script - host down vs host not on networkping 脚本 - 主机关闭与主机不在网络上
【发布时间】:2020-12-08 19:57:57
【问题描述】:

我有以下脚本,我试图区分已关闭的服务器和不再在网络上的服务器。 如果我在刚刚关闭的服务器的命令行上使用 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

【问题讨论】:

  • 对于第一个 if 语句,你得到一个 $? elif 语句为 1,因此它永远不会为 2。最好将变量设置为等于 ping 命令的返回值,即 pingerr=$?然后针对 $pingerr 运行 if 语句

标签: shell ksh ping


【解决方案1】:

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

#!/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

【讨论】:

    猜你喜欢
    • 2011-04-11
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 2021-06-14
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多