This tutorial will go over how to implement a simple script that uses Python and Linux Inotify API to monitor changes in a specific directory and log the console changes.
Before we get to the script, let us briefly discuss how Inotify works.
What is Inotify? How Does It Work?
Inotify is a Kernel subsystem that provides the mechanism to monitor events within the filesystem and report them to various applications that require them. Inotify is incredibly powerful because it works in the lower levels of the kernel and is customizable to expand functionality. Inotify can monitor changes in directories and individual files.
Although Inotify is powerful, it has some limitations. These limitations include:
- Inotify does not support Recursive directory watching
- It is only available in Linux Kernel
- Renaming of events using Inotify is not addressed directly.
However, Inotify is still a much better choice than Dnotify, its predecessor. Inotify is highly applicable in security applications like Antiviruses.
Now that we have the Inotify basic theory out of the way let us dive into building the script that’ll help us monitor for directory changes.
Installing Python and Watchdog
Before diving into the code, let us set up a few requirements, such as installing Python and the watchdog package.
To install Python3 on Debian, use the apt command as:
sudo apt-get install python3.7 python3-pip -y
To install the watchdog package, use the pip3 command as shown below:
sudo pip3 install watchdog
Writing the Script
The script we shall create in this tutorial is very simple. Consider the source code shown below:
import logging
import time
from watchdog.events import LoggingEventHandler
from watchdog.observers import Observer
def monitor():
# Add basic config
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
# get directory as argument
path = sys.argv[1] if len(sys.argv) > 1 else '.'
e_handler = LoggingEventHandler()
watch = Observer()
watch.schedule(e_handler, path, recursive=True)
watch.start()
try:
while True:
time.sleep(2)
except KeyboardInterrupt:
watch.stop()
watch.join()
monitor()
We start by importing the required modules, including watchdog. Next, we create a simple monitor function and set the configuration, such as the output format and the date. Next, we set the directory path arguments.
We then move to create an Observer object and set it to recursively monitor the changes to the directory specified unless a Keyboard interrupt is encountered (CTRL + C)
Finally, we call the function and run the script. You will get an output as shown below:
Conclusion
Using this tutorial, we have created a simple script that monitors the changes in a directory and constantly logs them to the console.