pyinotify

Inotify是一个事件驱动的通知机制,Inotify 提供一个简单的API,使用最小的文件描述符,并且允许细粒度监控。与 inotify 的通信是通过系统调用实现。

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class MyEventHandler(pyinotify.ProcessEvent):

#IN_ACCESS,即文件被访问
def process_IN_ACCESS(self, event):
LOG.debug(u"文件被访问:" + event.pathname)
#IN_MODIFY,文件被write
def process_IN_MODIFY(self, event):
removeStrInFile(event.pathname)
restoreFile(event.pathname)
#IN_ATTRIB,文件属性被修改,如chmod、chown、touch等
def process_IN_ATTRIB(self, event):
LOG.debug(u"文件属性被修改:" + event.pathname)
#IN_CLOSE_WRITE,可写文件被close
def process_IN_CLOSE_WRITE(self, event):
LOG.debug(u"可写文件被关闭:" + event.pathname)
#IN_CLOSE_NOWRITE,不可写文件被close
def process_IN_CLOSE_NOWRITE(self, event):
LOG.debug(u"不可写文件被关闭:" + event.pathname)
#IN_OPEN,文件被open
def process_IN_OPEN(self, event):
LOG.debug(u"文件被打开:" + event.pathname)
#IN_MOVED_FROM,文件被移走,如mv
def process_IN_MOVED_FROM(self, event):
LOG.info(u"文件被移走:" + event.pathname)
#IN_MOVED_TO,文件被移来,如mv、cp
def process_IN_MOVED_TO(self, event):
LOG.info( u"文件被移来:" + event.pathname)
#IN_CREATE,创建新文件
def process_IN_CREATE(self, event):
if event.pathname in filehash:
LOG.info(u"创建新文件:" + event.pathname)
restoreFile(event.pathname)
else:
removeFileOrDir(event.pathname)
#IN_DELETE,文件被删除,如rm
def process_IN_DELETiE(self, event):
LOG.info(u"文件被删除:" + event.pathname)
#IN_DELETE_SELF,自删除,即一个可执行文件在执行时删除自己
def process_IN_DELETE_SELF(self, event):
LOG.info(u"可执行文件删除:" + event.pathname)
#IN_MOVE_SELF,自移动,即一个可执行文件在执行时移动自己
def process_IN_MOVE_SELF(self, event):
LOG.info(u"可执行文件移动:" + event.pathname)
#IN_UNMOUNT,宿主文件系统被umount
def process_IN_UNMOUNT(self, event):
LOG.info(u"文件系统被umount:" + event.pathname)
#IN_CLOSE,文件被关闭,等同于(IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)
def process_IN_CLOSE(self, event):
LOG.debug(u"文件被关闭:" + event.pathname)
#IN_MOVE,文件被移动,等同于(IN_MOVED_FROM | IN_MOVED_TO)
def process_IN_MOVE(self, event):
LOG.info(u"文件被移动:" + event.pathname)

wm = pyinotify.WatchManager()
wm.add_watch(watchlist, pyinotify.ALL_EVENTS, rec=True)

# event handler
eh = MyEventHandler()

# notifier
notifier = pyinotify.Notifier(wm, eh)
notifier.loop()
打赏
0%