什么是inotify:
因此,典型的监控程序需要进行如下操作:
pyinotify包的安装
git clone https://github.com/seb-m/pyinotify.git
cd pyinotify/
python setup.py install
Inotify 可以监视的文件系统事件包括:
IN_ACCESS,即文件被访问
IN_MODIFY,文件被write
IN_ATTRIB,文件属性被修改,如chmod、chown、touch等
IN_CLOSE_WRITE,可写文件被close
IN_CLOSE_NOWRITE,不可写文件被close
IN_OPEN,文件被open
IN_MOVED_FROM,文件被移走,如mv
IN_MOVED_TO,文件被移来,如mv、cp
IN_CREATE,创建新文件
IN_DELETE,文件被删除,如rm
IN_DELETE_SELF,自删除,即一个可执行文件在执行时删除自己
IN_MOVE_SELF,自移动,即一个可执行文件在执行时移动自己
IN_UNMOUNT,宿主文件系统被umount
IN_CLOSE,文件被关闭,等同于(IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)
IN_MOVE,文件被移动,等同于(IN_MOVED_FROM | IN_MOVED_TO)
pyinotify使用例子
#!/usr/bin/env python
# encoding:utf-8
import os
from pyinotify import WatchManager, Notifier, \
ProcessEvent,IN_DELETE, IN_CREATE,IN_MODIFY
class EventHandler(ProcessEvent):
"""事件处理"""
def process_IN_CREATE(self, event):
print "Create file: %s " % os.path.join(event.path,event.name)
def process_IN_DELETE(self, event):
print "Delete file: %s " % os.path.join(event.path,event.name)
def process_IN_MODIFY(self, event):
print "Modify file: %s " % os.path.join(event.path,event.name)
def FSMonitor(path='.'):
wm = WatchManager()
mask = IN_DELETE | IN_CREATE |IN_MODIFY
notifier = Notifier(wm, EventHandler())
wm.add_watch(path, mask,auto_add=True,rec=True)
print 'now starting monitor %s'%(path)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break
if __name__ == "__main__":
FSMonitor('/home/firefoxbug')
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8