Posted 08.07.2005 | Updated 18.04.2008 | Contributed by Andy Mallett
OK, so I've successfully set up a working DHCP Service. Now I want my box to notify me, every time a new IP Address is allocated to a requesting host. This would be indicated by an increase in the size of the file /var/db/dhclient.leases, where ISC-DHCP registers its IP leases. Here's what I've come up with.
To begin with, this little six-line script..
#/bin/sh
#Andys File Size - Email Alerter Script
if [ $(ls -la | grep file.txt | cut -c 29-32) -gt "120" ]; then
mailx -s "The File is Bigger than 120" andym < file.txt
fi
The first line of code uses grep to pull the line containing the filename, from an ls -la listing and then uses cut to remove every character from that line except the file size. Naturally you've gotta play around with the character removal part on the command line until it's working and ready to incorporate into the script. Watch out if an increase in file size also creates another character, like 99 to 100 as this would mess the system up somewhat.
The second line uses the mailx command to email me with the specified subject heading and also copies the contents of the file into the email body. Nifty. With IMAP running on the server, the email client (Outlook) checks for mail from my workstation every 5 minutes.
The hardest thing for me was getting the syntax right so it would run smoothly from within the if statement. That's where the good old internet comes into its own, a glance at examples of code usage can save a lot of swearing.
So now I can modify things to reflect the required file details. The script itself will live in the /var/db/ directory alongside the file it's monitoring, so I don't have to worry about absolute paths. Behold dhalert.sh..
#/bin/sh
#Andys DHCP Alerter Script
if [ $(ls -la | grep dhclient.leases | cut -c 40-43) -gt "480" ]; then
mailx -s "New IP Address Allocated" andym < dhclient.leases
fi
The second part is to get the script to run all the time, continuously monitoring the file. The standard method is to use Cron. Here's my entry using the crontab -e command..
00,15,30,45 * * * * /var/db/dhalert.sh
So at the moment I'm getting it to check once every 15 minutes, every day/week/month/etc.. And that's about it. Naturally this file size monitoring method can be used to alert you about all sorts of system events. Wonderful!
See Part II for problem fixes and refinements..
|