If you need to monitor certain directories or even files you can use this excellent utility incrond which uses inotify to advise you of any changes that have been made to file system events. For example if you wanted to be sent an email when changes to the hosts file have been made or if a certain backup directory has been modified.
It consists of a daemon and a table manipulator, here are the list of inotify events that can be specified:
- IN_ACCESS File was accessed (read)
- IN_ATTRIB Metadata changed (permissions, timestamps, extended attributes, etc.)
- IN_CLOSE_WRITE File opened for writing was closed
- IN_CLOSE_NOWRITE File not opened for writing was closed
- IN_CREATE File/directory created in watched directory
- IN_DELETE File/directory deleted from watched directory
- IN_DELETE_SELF Watched file/directory was itself deleted
- IN_MODIFY File was modified
- IN_MOVE_SELF Watched file/directory was itself moved
- IN_MOVED_FROM File moved out of watched directory
- IN_MOVED_TO File moved into watched directory
- IN_OPEN File was opened
To install use your package managers.
sudo apt-get install incron
yum install incron
The configuration files in /etc are listed here with a brief description.
- /etc/incron.conf – incron config file
- /etc/incron.d/ – put config files here for incron to read.
- /etc/incron.allow – users allowed to use incron.
- /etc/incron.deny – users denied to use incron.
1. Create a simple file monitor:
Edit incrontab to create a monitor.
Run logger command when file created or deleted from /testincron directory:
/testincron IN_ALL_EVENTS logger "/testincron action for $# file"
Save and close the file. Now cd to /testincron and create a file:
$ cd /testincron
$ rm file1
To see message, enter:
$ sudo tail -f /var/log/messages
2. Monitor changes to the hosts file:
Edit incrontab to create a monitor (need to be root).
sudo incrontab -e
Add entry to check hosts file changes:
/etc/hosts IN_MODIFY /scripts/mailhostschange.sh $@/$#
Now create the mail command in the script file mailhostschange.sh that we are referencing above so that it can email us the alert when hosts file has changed.
mail -s "!!ALERT!! Hosts file modification has been detected" [email protected]
Make a change to the hosts file and an email should be received at [email protected] or whatever email address you specify. NOTE: It is assumed mailutils are installed and that the server can actually send mail via postfix/sendmail and so forth.