Thursday, June 20, 2013

Monitoring a directory for new file, deleted file, modified file with inotifywait and send thru email

On my setup, I am using CentOS

Add epel repo

yum install inotify-tools

create a bash script at /usr/ocal/bin/inotify_daemon.sh with entry below:

#!/bin/bash
pgrep inotifywait > /dev/null
if [ $? -eq 0 ]
then
exit
else
inotifywait --format '%w%f %e %T' --timefmt '%Y/%m/%d-%H:%M:%S' -e create,delete,modify,move -mrq /path/to/folder/ |while read file;do echo $file | mail -s "activity alert" myuser@mydomain.com; done &
fi

then create a cron entry at crontab or root cron.

* * * * * /usr/ocal/bin/inotify_daemon.sh

The cron will run and if  inotify_daemon.sh get accidentally killed, it will run it again. If already running, then it will exit. 

I assume that the server has a working smtp and tested to relay email to a ligit and working email system.

Sample email body once it will work is below:

/path/to/folder/test2 DELETE,ISDIR 2013/06/20-05:11:09

the notification that the folder has been deleted.