今天遇到这样一个问题,设计一个脚本,监控远程的一台机器(假设ip为123.23.11.21)的存活状态,当发现宕机时发一封邮件给你自己。
首先想到用户ping命令来探测远程机是否存活,但是如何知道呢,于是查了各大网页资料了解到这样一个程序:
#!/bin/bash
# blog:http://lizhenliang.blog.51cto.com
IP_LIST=
"192.168.18.1 192.168.1.1 192.168.18.2"
for
IP
in
$IP_LIST;
do
NUM=1
while
[ $NUM -
le
3 ];
do
if
ping
-c 1 $IP >
/dev/null
;
then
echo
"$IP Ping is successful."
break
else
# echo "$IP Ping is failure $NUM"
FAIL_COUNT[$NUM]=$IP
let
NUM++
fi
done
if
[ ${
#FAIL_COUNT[*]} -eq 3 ];then
echo
"${FAIL_COUNT[1]} Ping is failure!"
unset
FAIL_COUNT[*]
fi
done
[root@localhost ~]# if ping -c 1 192.168.247.130 >/dev/null;then echo "sucessful"; break; else echo "loss"; fi
loss
[root@localhost ~]# if ping -c 1 192.168.247.131 >/dev/null;then echo "sucessful"; break; else echo "loss"; fi
sucessful
loss
[root@localhost ~]# if ping -c 1 192.168.247.131 >/dev/null;then echo "sucessful"; break; else echo "loss"; fi
sucessful
原来是被“ping -c 1 192.168.247.130 >/dev/null”摒弃标准输出所迷惑,任务既然摒弃了怎么能判断,但看整个if语句才发现,这个位置的if...else语句相当于$?,于是明白了。你呢?