#!/bin/bash #version 1 #created by com`k #51cto ID:jingkonglanxing (净空蓝星) #脚本功能:实现输入一个标准网段,如192.168.0.0 24,其中24表示掩码,24和前面IP间有空格 read -p "请输入你要测试的网段:如192.168.0.0 24,只支持标准掩码8 16 和24:" string declare -i sum=0 ###sum 用于统计在线主机数目,及在统计过程中做数组OnlineHostlist的下标 quitScript() { echo "User Interrupt ,Quit..." echo "the total number of online hosts is $sum" echo "The online host are:" echo "${OnlineHostList[@]}" ###支持Ctrl+c中断 } declare -a OnlineHostList ###数组用于存放在线的主机 trap 'quitScript; exit 5' SIGINT subnet=`echo $string|cut -d"." -f1-3` cnetPing() { for i in {1..254}; do if ping -c 1 -n -i 0.01 -W 0.1 $subnet.$i &> /dev/null; then echo "$subnet.$i is up."; OnlineHostList=([$sum]=$subnet.$i) let sum=$sum+1 else echo "$subnet.$i is down." fi done } bcnetPing() { ##B类网络引用C类网络时,C类网络最后一个地址可以是255,因为255对于B类###网络来说不一定是广播地址 for m in {1..255}; do if ping -c 1 -n -i 0.01 -W 0.1 $subnet.$i &> /dev/null; then echo "$subnet.$i is up."; OnlineHostList=([$sum]=$subnet.$i) let sum=$sum+1 else echo "$subnet.$i is down." fi done } bnetPing() { for j in {0..254}; do bcnetPing $subnet.$j done cnetPing $subnet.255 ####以防出现255.255结尾的广播地址 } abnetPing() { for l in {0..255}; do bcnetPing $subnet.$j done cnetPing $subnet.255 ####以防出现255.255结尾的广播地址 } anetPing() { for m in {0..254}; do abnetPing $subnet.$m done bnetPing $subnet.255 ####原理同上 } netType=`echo $string|cut -d" " -f2` if [[ $netType == 8 ]];then anetPing $netType elif [[ ${netType} == 16 ]]; then bnetPing $(echo $subnet | cut -d'.' -f1,2) elif [[ $netType == 24 ]]; then cnetPing $(echo $subnet | cut -d'.' -f1-3) else echo "Wrong" exit 2 fi echo "the total number of online hosts is $sum" echo "The online host are:" echo "${OnlineHostList[@]}"