ref : http://www.jb51.net/article/33772.htm
# cat ping.sh
#! /bin/bash
:<<!
The purpose of this shell script is to detect whether can ping through
the specified host or not. And will record the results in $filename and
$badFileName.
!
filename="/home/XXX/XXXX.txt";
badFileName="/home/xxxx/xxxx.txt"
if [ -f $filename ]; then
rm -fr $filename;
touch $filename;
else
touch $filename;
fi
if [ -f $badFileName ]; then
rm -fr $badFileName;
touch $badFileName;
else
touch $badFileName;
fi
host="www.baidu.com";
#host="x.x.x.x";
#host="www.baidu11111222222222222.com";
ping_count=3;
while true; do
ping_result=`ping $host -c $ping_count 2>&1 |grep "unknown host"`
if [ $? -eq 0 ]; then
echo "本次检测结果---->$ping_result";
echo "本次检测结果---->$ping_result" >> $badFileName
echo "`date "+%Y%m%d %H:%M:%S"`--->$ping_result" >>$badFileName
else
ping_result=`ping $host -c $ping_count |tail -2 |head -1`
:<<!
echo $ping_result
ping: unknown host www.baidu11111222222222222.com
!
#取成功条数
#3 packets transmitted, 3 received, 0% packet loss, time 10010ms
#succ_ping=`echo ${"ping_result":23:1}`
succ_ping=`expr substr "$ping_result" 24 1`
#取失败百分比
#3 packets transmitted, 0 received, 100% packet loss, time 2014ms
#loss_ping=`echo ${ping_result:46:4}`
loss_ping=`expr substr "$ping_result" 36 4`
if [ $succ_ping -eq $ping_count ]; then
echo "本次检测结果---->$host服务器ping检测正常";
echo "本次检测结果---->$host服务器ping检测正常" >> $filename
echo "`date "+%Y%m%d %H:%M:%S"`--->$host服务器ping检测正常" >> $filename
else
echo "本次检测结果---->$host服务器有丢包现象,丢包率为:$loss_ping";
echo "本次检测结果---->$host服务器有丢包现象,丢包率为:$loss_ping" >> $badFileName
echo "`date "+%Y%m%d %H:%M:%S"`--->$host服务器有丢包现象,丢包率为:$loss_ping" >>$badFileName
fi
fi
# sleep two seconds, and go on detecting.
sleep 2
done