Tuesday, July 10, 2007

Monitoring changes to a directory tree in Linux

If you are managing a multi-user Linux box , as a sysadmin you'd like to be informed of changes in certain directory trees. Inotify is often suggested as a solution. But that might be overkill if you aren't concerned about file changes and just want to monitor a directory tree - have any dirs been updated, any created, or have any dirs been deleted.

The solution is surprisingly simple. It's rsync. But rsync with a twist.

The steps involved are

1. rsync JUST the directory tree - no files - to another area.
2. pipe the output into a mail to yourself
3. cronjob it.


This is how i rsync the dir tree of a dir that i want to monitor


> pico monitortree

#!/bin/bash
rsync -av --delete --include '*/' --exclude '*' /websites/ /home/jflavin/sitetree/ | mail -s "directory tree report" justinf@gmail.com

my websites folder is rsync'ed across to /home/jflavin/sitetree - but only the directory tree. no files are rsync'ed. its a bash script, so you'll need to chmod it to make it executable.

here's the cronjob entry:


> crontab -e

15 * * * * /cronscripts/monitortree


so my monitoring script kicks off every hour at 15 minutes past. and the output is mailed to me.
note the rsync statement above - it only rsyncs the directory tree. NOT the files. so its very fast. also, if somebody adds a file to a dir, the dir time stamp changes - and that'll be rsync'ed , thus alerting you to a file change - without the file being rsync'ed itself.