在linux系统中,可以使用ping命令检测主机状态,根据返回的状态信息,判断当前主机是活动,还是已经当掉了。
一,可以进行简单交互的ping函数
复制代码代码示例:
#!/bin/bash
#note:ping monitor #by www.jbxue.com 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
代码说明:
调用示例,如下图:
二,ping指定ip段的shell脚本
复制代码代码示例:
#!/bin/bash
#edit by www.jbxue.com 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
代码说明:
调用示例,如下图: |