Monitoring a filesystem with Python and Pyinotify
Pyinotify is a Python library for monitoring filesystem events on Linux through the inotify Linux kernel subsystem. It can monitor when a file is created, accessed, deleted, modified, etc. For a full list of Pyinotify events see the documentation.
Install Pyinotify¶
- Install pip
- Install Pyinotify
$ sudo pip install pyinotify
Example¶
import pyinotify
class MyEventHandler(pyinotify.ProcessEvent):
def process_IN_ACCESS(self, event):
print "ACCESS event:", event.pathname
def process_IN_ATTRIB(self, event):
print "ATTRIB event:", event.pathname
def process_IN_CLOSE_NOWRITE(self, event):
print "CLOSE_NOWRITE event:", event.pathname
def process_IN_CLOSE_WRITE(self, event):
print "CLOSE_WRITE event:", event.pathname
def process_IN_CREATE(self, event):
print "CREATE event:", event.pathname
def process_IN_DELETE(self, event):
print "DELETE event:", event.pathname
def process_IN_MODIFY(self, event):
print "MODIFY event:", event.pathname
def process_IN_OPEN(self, event):
print "OPEN event:", event.pathname
def main():
# watch manager
wm = pyinotify.WatchManager()
wm.add_watch('/var/log', pyinotify.ALL_EVENTS, rec=True)
# event handler
eh = MyEventHandler()
# notifier
notifier = pyinotify.Notifier(wm, eh)
notifier.loop()
if __name__ == '__main__':
main()
Results:
MODIFY event: /var/log/auth.log MODIFY event: /var/log/syslog MODIFY event: /var/log/syslog MODIFY event: /var/log/auth.log MODIFY event: /var/log/auth.log MODIFY event: /var/log/syslog MODIFY event: /var/log/auth.log MODIFY event: /var/log/syslog MODIFY event: /var/log/auth.log OPEN event: /var/log/munin/munin-update.log MODIFY event: /var/log/munin/munin-update.log MODIFY event: /var/log/munin/munin-update.log MODIFY event: /var/log/munin/munin-node.log MODIFY event: /var/log/munin/munin-update.log MODIFY event: /var/log/munin/munin-update.log CLOSE_WRITE event: /var/log/munin/munin-update.log OPEN event: /var/log/munin/munin-limits.log MODIFY event: /var/log/munin/munin-limits.log CLOSE_WRITE event: /var/log/munin/munin-limits.log OPEN event: /var/log/munin/munin-graph.log MODIFY event: /var/log/munin/munin-graph.log CLOSE_WRITE event: /var/log/munin/munin-graph.log OPEN event: /var/log/munin/munin-html.log MODIFY event: /var/log/munin/munin-html.log CLOSE_WRITE event: /var/log/munin/munin-html.log MODIFY event: /var/log/auth.log MODIFY event: /var/log/auth.log MODIFY event: /var/log/syslog MODIFY event: /var/log/auth.log MODIFY event: /var/log/auth.log MODIFY event: /var/log/syslog MODIFY event: /var/log/auth.log ...
Related posts
- How to get the filename and it's parent directory in Python — posted 2011-12-28
- How to remove ^M characters from a file with Python — posted 2011-10-03
- Options for listing the files in a directory with Python — posted 2010-04-19
- os.path.relpath() source code for Python 2.5 — posted 2010-03-31
- A hack to copy files between two remote hosts using Python — posted 2010-02-08