Python

How Do I See Directory Changes in Python?

In some instances, especially in critical and restricted locations of the filesystem, it can be helpful to know when things change and what has changed. Using Linux Inotify tools and Python, we can view and log the changes that happen within the system.

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 update

sudo apt-get install python3.7 python3-pip -y

To install the watchdog package, use the pip3 command as shown below:

https://pypi.org/project/watchdog/

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 sys
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list