天天看点

linux ping shell脚本,分享几个ping主机是否存活的shell脚本(图文)

在linux系统中,可以使用ping命令检测主机状态,根据返回的状态信息,判断当前主机是活动,还是已经当掉了。

经过一翻努力,实现了以下几个脚本,分享给大家。

一,可以进行简单交互的ping函数

复制代码 代码示例:

#!/bin/bash

#note:ping monitor

#by www.jquerycn.cn 2013-7-22

set -u

#set -x

ping_fun()

{

d_network=192.168.1

echo -n "input the network(default $d_network):"

read network

: ${network:=$d_network}

echo "network:$network"

d_hostip_beg=1

d_hostip_end=254

echo -n "input the hostip(default $d_hostip_beg $d_hostip_end):"

read hostip_beg hostip_end

: ${hostip_beg:=$d_hostip_beg}

: ${hostip_end:=$d_hostip_end}

echo "hostip_beg:$hostip_beg"

echo "hostip_end:$hostip_end"

count=3

for ((hostip=$hostip_beg;hostip<=$hostip_end;hostip++));do

host=$network.$hostip

echo "--- beginning ping $host ---"

ping -c $count $host &>/dev/null

if [ $? = 0 ];then

echo "$host is up"

else

sleep 3

ping -c $count $host &>/dev/null

if [ $? = 0 ];then

echo "$host is up"

else

echo "$host is down"

fi

fi

done

#echo "done"

exit 0

}

main()

{

echo "----begin Ping----"

ping_fun

}

main

exit 0

代码说明:

1,echo -n "input the network(default $d_network):"

此句是指定要检测的网段,比如默认为192.168.1,可以指定待检测的网段为192.168.8等。

2,echo -n "input the hostip(default $d_hostip_beg $d_hostip_end):"

此句是指定要检测的主机范围,比如要检测IP地址为192.168.8.1-30的主机,此处则输入1 30,记得数字之间要有一个空格。

3,

sleep 3

ping -c $count $host &>/dev/null

第一句是暂停3秒,即检测主机时的时间间隔。

第二句为本脚本的关键语句,-c $count为ping的次数,本例中为3次。实际网络环境中,如果只ping一次可能造成误报,所以可以多ping几次。

&>/dev/null将输出写入空设备文件。

调用示例,如下图:

linux ping shell脚本,分享几个ping主机是否存活的shell脚本(图文)

二,ping指定ip段的shell脚本

复制代码 代码示例:

#!/bin/bash

#edit by www.jquerycn.cn

for a in {1..254}

do

if ping -w 1 -c 1 192.168.1.$a | grep "100%" >/dev/null

then

echo "192.168.1.$a is Not reachable"

else

echo "192.168.1.$a is reachable"

fi

done

代码说明:

1,for a in {1..254}

这句如果不起作用的话,可以尝试修改为$(seq 1 254)或使用for((;;))语句。

2,if ping -w 1 -c 1 192.168.1.$a | grep "100%" >/dev/null

ping一次变量对应的ip地址,-c 1表示ping一次;–w –l 表示等待超时的时间为1秒。

调用示例,如下图:

linux ping shell脚本,分享几个ping主机是否存活的shell脚本(图文)