Skip to content

Instantly share code, notes, and snippets.

@microlinux
Created February 12, 2015 08:02
Show Gist options
  • Save microlinux/74fc92f85738bffcdd5a to your computer and use it in GitHub Desktop.
Save microlinux/74fc92f85738bffcdd5a to your computer and use it in GitHub Desktop.
Ping IPs by subnet and show simple up/down status
#!/bin/bash
# [user@server ~]$ sping.sh 70.120.121.0/29
# 70.120.121.1 down
# 70.120.121.2 up
# 70.120.121.3 up
# 70.120.121.4 up
# 70.120.121.5 up
# 70.120.121.6 up
# configuration variables
# absolute path to directory containing sping.sh, without trailing /
DIR="/usr/local/bin"
# maximum number of concurrent pings
MAX_WORKERS=50
# support programs
declare -A hosts
hosts[30]=1
hosts[29]=5
hosts[28]=13
hosts[27]=29
hosts[26]=61
hosts[25]=125
hosts[24]=253
hosts[23]=509
hosts[22]=1021
hosts[21]=2045
hosts[20]=4093
hosts[19]=8189
hosts[18]=16381
hosts[17]=32765
hosts[16]=65533
hosts[15]=131069
hosts[14]=262141
hosts[13]=524285
hosts[12]=1048573
hosts[11]=2097149
hosts[10]=4194301
hosts[9]=8388605
hosts[8]=16777213
function show_help()
{
echo "usage: sping.sh 192.168.0.0/24"
}
function ip2int()
{
int=0
for octet in ${1//./ }
do
int=$((256*$int+$octet))
done
echo $int
}
function int2ip()
{
echo "$(($1 / 16777216)).$(($(($1 % 16777216)) / 65536)).$(($(($1 % 65536)) / 256)).$(($1 % 256))"
}
function ping_host()
{
ping -c3 -i.2 -W1 -q "$1" 2> /dev/null | grep rtt &> /dev/null
if [ $? -eq 0 ]
then
echo "$1 up"
else
echo "$1 down"
fi
}
function build_list()
{
list=""
start=$(($(ip2int $1)+1))
stop=$(($start+${hosts[$2]}))
for ip in $(seq "$start" "$stop")
do
list+="$(int2ip $ip)\n"
done
echo "$list"
}
# main program
if [ "$1" = "worker" ]
then
result=$(ping_host $2)
echo "$result"
else
IFS='/'
read -a INPUT <<< "$1"
unset IFS
if [ "${#INPUT[@]}" -ne 2 ]
then
show_help
exit 1
elif [ "${INPUT[1]}" = "-h" -o "${INPUT[1]}" = "--help" ]
then
show_help
exit 0
elif [ "${INPUT[1]}" -lt 8 -o "${INPUT[1]}" -gt 30 ]
then
echo "invalid subnet mask"
exit 1
fi
list=$(build_list ${INPUT[0]} ${INPUT[1]})
echo -e "$list" | xargs -n 1 -I ^ -P "$MAX_WORKERS" $DIR/sping.sh worker ^ | sort -t . -k 3,3n -k 4,4n
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment