shell - 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
解决方案
我根据拉曼的建议修改了我的脚本,如下所示,这很有效。谢谢拉曼!!
#!/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
推荐阅读
- hpc - 在 SLURM 中的多个目录上运行一个脚本的首选方法
- ember.js - Ember 重定向旧路线
- mysql - Mysql 使用 Order by Clause 性能非常慢
- java - 将 SVN 用于 Spring Cloud Config 服务器时出错
- ios - 在异步加载中重新加载数据
- spring - Mapped Super 类中的 Eager fetch 属性
- angular - 将 ion-fab 按钮水平居中对齐
- javascript - 如何使手风琴类默认扩展
- http-status-code-404 - 无效查询参数的 HTTP 404 与 400
- c# - C# Linq 查找匹配条件的记录,如果找到该记录,则返回所有相关记录