Detect the target host network whether can ping through or not(shell script)

109 篇文章 0 订阅
85 篇文章 0 订阅

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值