Script to monitor assigned IP address on a local network

Jun 19th, 2009 | By Roma | Category: CentOS

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:

# yum install nmap

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 !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!bin/sh
 
cd  /path/to/script
i=0
unset arr
 
#Read the hostlist.dat file from a previous run and store it to an array
while read line
do
  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 directory
nmap -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 network
while read line  #read the just created hostlist.dat file one line at the time
do
  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
  fi
done < hostlist.dat
 
j=0
#second loop to detect hosts disconnected from the local network since last run
while [[ $j -lt ${#arr[*]} ]] #read the array
do
  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
  fi
done

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

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

Leave Comment