The script: chkdir.py

Description
The script emails differences on a directory’s listing. So if you’re monitoring changes in a specific directory you can use this script. Run it under CRON every 5 minutes and on any changes you’ll get an email looking like this:

screenshot-changes-in-home-gerard-files-python-chkdir-testdir-kontact1

Configuration
Not much. Change the email related variables in the config section in the header of the script. Example:

Explanation
The script takes the absolute path to the directory that needs monitoring as the first argument. And an optional second argument called ‘verbose’ if you want specifics. If all goes well during execution, and run without ‘verbose’, the script only outputs via email. The reason? This precludes your CRON daemon from doing unnecessary logging.

The previous listing of a directory, to which the new listing is compared, is stored in a file. The file is given the same name as the monitored directory. It has a suffix called ‘.dirlist’ and the file is stored in the parent directory. See ‘Issues’ at the end for more details.

The script only sends output to STDOUT during the initial stage when you start to monitor a directory. The script cops out when: the parent directory is not writable, the given path does not exist, creating the first snapshot (dirlist) of a directory, etc. Since this is all done from the commandline at first, knowing what’s going at this stage is important. After that the script turns quiet.

Examples
Some startup failure messages.

No write privileges:

$ ./chkdir.py /tmp/
Sorry, I do not have permission to write in parent directory

First run on a directory:

$ ./chkdir.py /home/gerard/temp/testdir/
No previous listfile, created new one, will do diff on next run

As said, after that it turns quiet, except when using ‘verbose’. Then your commandline output looks like this:

$ ./chkdir.py /home/gerard/temp/testdir verbose
New list
['Screenshot-GP-net xe2x80xba Dashboard.png', 'GP-net xe2x80xba Dashboard boe.png']

Old list
['Screenshot-GP-net xe2x80xba Dashboard.png', 'GP-net xe2x80xba Dashboard boe.png', 'Screenshot-Google.png']

Removed:
set(['Screenshot-Google.png'])

The funky escaped values are unicode utf-8 characters. Like I said if you use verbose you get specifics. Not to worry though, any characters allowed in your file or directory names are correctly displayed when you get the output emailed (assuming your mail client supports them).

Issues
Due to storing the file with the previous list in its parent directory it currently is not possible to monitor the ‘root’ of you file system. A different approach would be to generate an md5 hash of the path and put the ‘.dirlist’ file in “/tmp”. But that would result in people being able to obtain info on file system parts where they might not be allowed themselves.

Any suggestions on a better approach to store the previously made listing are welcome.

Regards,

Gerard.