以47.94.215.0/24网段为例,判断该网段内所有主机在线与否,以能ping通视为在线,反之离线。脚本名为ping.sh
将其结果保存至/tmp/ping目录下,在线主机的保存文件为/tmp/ping/uphosts.ttx,离线主机的保存文件为/tmp/ping/downhosts.txt。
1 #!/bin/bash 2 #description:Judge online hosts and downhosts,and count 3 #__Author__:lushenle 4 #Version:0.0.1 5 # 6 ls -d /tmp/ping 7 if [ $? -eq 0 ];then 8 ls -f /tmp/ping/uphosts.txt 9 if [ $? -eq 0 ];then 10 mv /tmp/ping/uphosts.txt{,.bak} 11 touch /tmp/ping/uphosts.txt 12 else 13 touch /tmp/ping/uphosts.txt 14 fi 15 ls -f /tmp/ping/downhosts.txt 16 if [ $? -eq 0 ];then 17 mv /tmp/ping/downhosts.txt{,.bak} 18 touch /tmp/ping/downhosts.txt 19 else 20 touch /tmp/ping/downhosts.txt 21 fi 22 else 23 mkdir -p /tmp/ping/ 24 touch /tmp/ping/uphosts.txt 25 touch /tmp/ping/downhosts.txt 26 fi 27 28 echo "#description:47.94.215.0/24 uphosts." > /tmp/ping/uphosts.txt 29 echo "#description:47.94.215.0/24 downhosts." > /tmp/ping/downhosts.txt 30 31 net='47.94.215' 32 declare -i i 33 34 uphosts=0 35 downhosts=0 36 37 for i in {1..254};do 38 ping -c 1 -w 1 ${net}.${i} &> /dev/null 39 if [ $? -eq 0 ];then 40 echo "${net}.${i} is up." >> /tmp/ping/uphosts.txt 41 let uphosts++ 42 else 43 echo "${net}.${i} is down!" >> /tmp/ping/downhosts.txt 44 let downhosts++ 45 fi 46 done 47 48 echo "Uphosts is:$uphosts." >> /tmp/ping/uphosts.txt 49 echo "Downhosts is:$downhosts." >> /tmp/ping/downhosts.txt
~]# bash -n /PATH/TO/ping.sh #检查是否存在语法错误
~]# bash -x /PATH/TO/ping.sh #查看执行过程