首页 > 代码库 > 通过Ping判断监控主机的存活

通过Ping判断监控主机的存活

通过Ping命令监控主机是否存活,只要一次ping通则为正常,如果ping失败则继续ping,三次不通就认为主机宕机或网络有问题,这时就可以发送邮件告警了。

方法一:

说明:如果判断的机器数量不多,可以每台机器Ping三次判断

#! /bin/bash

if [ -e /tmp/c.txt ];then

    rm -rf /tmp/c.txt

    touch /tmp/c.txt

else

    touch /tmp/c.txt

fi

if [ -e /tmp/d.txt ];then

    rm -rf /tmp/d.txt

    touch /tmp/d.txt

else

    touch /tmp/d.txt

fi


for i in `seq 100 105`

do

    ip=192.168.2.$i

    ping -c 3 $ip > /dev/null 2>&1

    if [ $? -eq 0 ];then

          echo $ip "is on line" >> /tmp/c.txt

    else

          echo $ip "is offline" >> /tmp/d.txt

    fi

done

技术分享


方法二:

说明:将错误次数放到fail_count变量来判断是非Ping失败三次

#! /bin/bash

if [ -e /tmp/c.txt ];then

    rm -rf /tmp/c.txt

    touch /tmp/c.txt

else

    touch /tmp/c.txt

fi

if [ -e /tmp/d.txt ];then

    rm -rf /tmp/d.txt

    touch /tmp/d.txt

else

    touch /tmp/d.txt

fi

for i in `seq 100 105`

do

    ip=192.168.2.$i

    fail_count=0

    for ((i=1;i<=3;i++))

    do

        if ping -c 1 $ip > /dev/null;then

            echo "$ip is online" >> /tmp/c.txt

            break

        else

            #echo "$ip ping is offline $i"

            let fail_count++

        fi

done

        if [ $fail_count -eq 3 ];then

            echo "$ip is offline" >> /tmp/d.txt

        fi

done


技术分享


方法三:

说明:将错误ip放到数组里面判断是否Ping失败三次

#! /bin/bash

if [ -e /tmp/c.txt ];then

    rm -rf /tmp/c.txt

    touch /tmp/c.txt

else

    touch /tmp/c.txt

fi

if [ -e /tmp/d.txt ];then

    rm -rf /tmp/d.txt

    touch /tmp/d.txt

else

    touch /tmp/d.txt

fi


for i in `seq 100 105`

do

    ip=192.168.2.$i

    num=1

    while [ $num -le 3 ]

    do

        if ping -c 1 $ip > /dev/null;then

            echo "$ip is online" >> /tmp/c.txt

            break

        else

            # echo "$ip ping is offline $num"

            fail_count[$num]=$ip

            let num++

        fi

done

        if [ ${#fail_count[*]} -eq 3 ];then

            echo "${fail_count[1]} is offline" >> /tmp/d.txt

        fi

done

技术分享


方法四:

说明:利用for循环,因为continue,如果ping通就跳出循环,,如果不跳出就会打印ping失败

#! /bin/bash

if [ -e /tmp/c.txt ];then

    rm -rf /tmp/c.txt

    touch /tmp/c.txt

else

    touch /tmp/c.txt

fi

if [ -e /tmp/d.txt ];then

    rm -rf /tmp/d.txt

    touch /tmp/d.txt

else

    touch /tmp/d.txt

fi


ping_success_status(){

    if ping -c 1 $ip > /dev/null;then

        echo "$ip is online" >> /tmp/c.txt

        continue

    fi

}

for i in `seq 100 105`

do

    ip=192.168.2.$i

    ping_success_status

    ping_success_status

    ping_success_status

    echo "$ip is offline" >> /tmp/d.txt

done


技术分享

下面这个截图,跟上面的图片有一点区别:

技术分享

ifconfig |awk -F [:a-Z" "]+ ‘NR==2{print $2}‘可以获取IP地址



本文参考一下文章:

  1. http://lizhenliang.blog.51cto.com/7876557/1736770

  2. http://blog.csdn.net/zhuying_linux/article/details/6822987

  3. http://12100846.blog.51cto.com/12090846/1863259

通过Ping判断监控主机的存活