Rabu, 08 Juni 2011

Script to monitor assigned IP address on a local network

I wanted to monitor all assigned IP addresses on my local network. Since I have a hardware router/DHCP server, looking at the DHCP table was not an option. So I wrote a script on a CentOS Linux server.

You might need to install nmap on your distribution before using the script. On CentOS, install nmap with:

The script pings all addresses in a specific range and looks at who has connected/disconnected since the last time the script was run. Whenever activity is detected, it is sent by mail. Of course the accuracy of the results depends on how often the script is run. I use a crontab entry for this purpose.

Don’t forget to change the path, the IP range, the email address, etc… before using !

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061#!bin/sh cd /path/to/scripti=0unset arr #Read the hostlist.dat file from a previous run and store it to an arraywhile read linedo arr[i]=$line (( i=$i+1 ))done < hostlist.dat #ping all IP's in a range and redirect the output to hostlist.dat in the same directorynmap -sP 192.168.0.1-255 | grep 192.168.0. | awk -F ' appears' '{ print $1 }' > hostlist.dat #first loop to detect new hosts on the local networkwhile read line #read the just created hostlist.dat file one line at the timedo j=0 found=0 while [[ $j -lt ${#arr[*]} ]] #read the array do if [[ ${arr[$j]} = $line ]] #compare the hostlist.dat file to the array then found=1 fi (( j=$j+1 )) done if [[ $found = 0 ]] then lineip=$line line=`echo $line | egrep -o '192.[0-9.]+'` #return ip adress line=`nmblookup -A $line` #retreive machine name #I chose to send a mail, but you can change this line to whatever suits you echo $line | mailx -s "INFO: $lineip now connected to the local network!!!" name@domain.com fidone < hostlist.dat j=0#second loop to detect hosts disconnected from the local network since last runwhile [[ $j -lt ${#arr[*]} ]] #read the arraydo found=0 while read line #read the just created hostlist.dat file one line at the time do if [[ ${arr[$j]} = $line ]] #compare the hostlist.dat file to the array then found=1 fi done < hostlist.dat line=${arr[$j]} (( j=$j+1 )) if [[ $found = 0 ]] then lineip=$line line=`echo $line | egrep -o '192.[0-9.]+'` #return ip address, no nmblookup here since machine is disconnected #I chose to send a mail, but you can change this line to whatever suits you echo $lineip | mailx -s "INFO: $line now disconnected from the network!!!" name@domain.com fidone

And this is the crontab entry for running the script every two minutes.

*/2 * * * * . /path/to/script/hostlist > /dev/null 2 >& 1

View the original article here

Tidak ada komentar:

Posting Komentar