Saturday, June 4, 2011

Automate log monitoring and get email notifications with swatch

The swatch program (simple watcher) can monitor all sorts of logs and respond to certain events when they occur. Its concept is quite simple. Swatch will monitor a logfile for us , for example, /var/log/syslog, and when a specific event occurs (these events are configured in the swatch config file) and are logged in the log file, swatch can respond by executing a program, sending an email to a sysadmin or sending messages to the console where swatch is being run.

A simple example of swatch in action. If you are the sole sysadmin of a webserver, you would probly want to be notified if someone attempts to try to log into your server (could be over ssh or other authentication services). Being the sole admin of the webserver, no one else should have any business being on the system. Anyone but the admin attempting to login to the system obviously doesn't belong there and may have bad intentions. In this case, you can set up swatch to monitor the auth.log file for failed logon attempts and succesful logon attempts and then send you an email whenever their is attempts from anyone to log in. Of course this will notify you even when you log on to the machine, therefore this might be more practical if you have an unattended system (maybe you are on vacation or away on business).

I use an email program which is actually a perl script, called sendemail. On a debian based system, you can install it via apt-get install sendemail. Likewise, to install swatch, apt-get install swatch. Once both are installed, a simple configuration for swatch is as follows

watchfor /sshd/
echo bold
bell 3
exec "/usr/bin/sendemail -s smtp.live.com:25 -f youremail@hotmail.com -xu youremail@hotmail.com -xp your_hotmail_pass -u "Log alert" -m "Possible SSHD login attemp" -t youremail@hotmail.com -s smtp.live.com"


Save the above to a text file with an appropriate name such as swatch.conf

Then we can execute swatch like this:
# swatch --config-file=/path/to/swatch.conf --script-dir=/path/to/your_config_dir --examine=/var/log/auth.log

Whenever someone attempts to login to your sshd server, the sshd daemon will log the login attemp in /var/log/auth.log. The swatch program will monitor the auth.log file for the string sshd and whenever it gets a match, it will leave a notification on the console and then send an email to youremail@hotmail.com. The swatch program understands regex expressions so you can perform more advanced matches instead of a simple string like sshd.

No comments:

Post a Comment