Incron is a daemon which monitors filesystem events and executes commands defined in system and user tables. It can be installed on all major distributions using each distribution’s default package manager.
Why I needed it?
I’m using as a web server for my vps server. That being said, the web root folder where I add files to be accessible via web, due to security reasons it has ownership as : + 750 mode for folders and 640 for files. Since I do a lot of copying from one server to another, usually the files that I copy from another server to my server, have a default ownership of root:root (since I login via ssh with a regular user, then sudo su – (too damn lazy to add sudo before every command).
If I want to download that file from my own server via HTTP let’s say, I have to chown : that file (otherwise I’ll get a read error because of the ownership). And this can become annoying sometimes. So I was looking for some sort of solution to be able do that automatically. To be more specific, if a new file is created or copied in my web root folder, then to automatically execute a chown : on that file. I played a little bit with the inotify-tools and inotify-wait but I didn’t like it entirely. Then I decided to use incron.
The syntax is pretty similar with the one from cron (crontab).
The format is as follows:
<path> <mask> <command>
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 (*)
Command takes the following arguments:
$$ dollar sign
$@ watched filesystem path (see above)
$# event-related file name
$% event flags (textually)
$& event flags (numerically)
For more information please consult the program’s man page.
So let’s take this scenario for example: My web root folder is /var/www/html. So I want to monitor that folder and if a file is copied there, modified, created, edited etc, when that happens, incron will automatically execute /usr/bin/chown nginx:nginx file.
That can be achieved like that:
Then add the entry bellow and save:
/var/www/html IN_MODIFY /usr/bin/chown nginx:nginx "$@/$#"
Now if a new file is created/edited/modified/copied to the /var/www/html/ folder the /usr/bin/chown : command will be automatically executed on that file.
Pretty simple isn’t it?