#!/bin/bash
###################
# Check Active Host#######
###################
function CheckInput(){
if [ $# -ne 1 ] ; then
return 1
else
return 0
fi
}
function CheckIp(){
/bin/ipcalc -s -c $1 &>/dev/null
return $?
}
function PingIp(){
ping -c 2 -W 2 $1 &>/dev/null
if [ $? -eq 0 ] ; then
echo $1 >> $TMP_ACTIVE
else
echo $1 >> $TMP_DOWN
fi
}
function PingAll(){
PrefixIP=$(echo $1|awk -F '.' '{print $1"."$2"."$3"."}')
for ip in {1..254}
do
IP="${PrefixIP}${ip}"
PingIp $IP &
done
}
function SelectPing(){
ENDIP=$(echo $1|awk -F '.' '{print $NF}')
if [ $ENDIP -eq 0 -o $ENDIP -eq 255 ] ; then
PingAll $*
else
PingIp $*
fi
}
function SortIp(){
while :
do
PING_NUM=$(ps -ef|grep ping|grep -v 'grep'|wc -l)
if [ $PING_NUM -eq 0 ] ; then
`cat $TMP_ACTIVE|sort -t '.' -k 4 -n > /tmp/active.host`
`cat $TMP_DOWN|sort -t '.' -k 4 -n > /tmp/down.host`
rm -f $TMP_ACTIVE
rm -f $TMP_DOWN
break
fi
done
}
function Show(){
ACTIVEIP=$(cat /tmp/active.host)
DOWNIP=$(cat /tmp/down.host)
if [ -s "/tmp/active.host" ] ; then
echo "Active Host:"
echo $ACTIVEIP|tr " " "\n"
else
echo "Down Host:"
echo $DOWNIP|tr " " "\n"
fi
}
function main(){
CheckInput $*
if [ $? -ne 0 ] ; then
echo -e $"USAGE: $0 {ipaddress}\nExample:\n$0 192.168.1.10 will check 192.168.1.10 only\n$0 192.168.1.0 will check 192.168.1.1 - 192.168.1.254 "
else
CheckIp $*
if [ $? -ne 0 ] ; then
echo "Please input correct ip address . such as 192.168.1.10 or 192.168.1.0"
else
TMP_ACTIVE=$(mktemp)
TMP_DOWN=$(mktemp)
>/tmp/active.host
>/tmp/down.host
SelectPing $*
SortIp
Show
rm -f /tmp/active.host
rm -f /tmp/down.host
fi
fi
}
main $*