在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将輸出寫入空裝置檔案。
調用示例,如下圖:

二,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秒。
調用示例,如下圖: