python监视ubuntu目录

EventHandler类的函数重载

process_后面加上下面的内容,需要那个功能就重载那个函数。

事件类型 说明
IN_ACCES 文件被访问

IN_MODIFY|文件被修改
IN_ATTRIB|文件属性被修改
IN_CLOSE_WRITE|以可写方式打开的文件被关闭
IN_CLOSE_NOWRITE|以不可写方式打开的文件被关闭
IN_OPEN|文件被打开
IN_MOVED_FROM|文件被移出监控的目录
IN_MOVED_TO|文件被移入监控着的目录
IN_CREATE|在监控的目录中新建文件或子目录
IN_DELETE|文件或目录被删除
IN_DELETE_SELF|自删除,即一个可执行文件在执行时删除自己
IN_MOVE_SELF|自移动,即一个可执行文件在执行时移动自己

代码

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import pyinotify
from db import *

homepath = "/var/netdisk"

class NetdiskEventHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
# create
# <Event dir=False mask=0x100
# maskname=IN_CREATE name=aaa
# path=/var/netdisk/admin/root
# pathname=/var/netdisk/admin/root/aaa
# wd=5 >
print(event)
if event.dir: # dir
dir
else: # file
2
print("process_IN_CREATE:", event.pathname)
return

def process_IN_DELETE(self, event):
# delete
# <Event dir=False mask=0x200
# maskname=IN_DELETE name=aaa
# path=/var/netdisk/admin/root
# pathname=/var/netdisk/admin/root/aaa
# wd=5 >
print(event)
if event.dir: # dir
dir
else: # file
2
print("process_IN_DELETE:", event.pathname)
return

def process_IN_MOVED_TO(self, event):
# move to
print(event)
# <Event cookie=80721 dir=False
# mask=0x80 maskname=IN_MOVED_TO
# name=dd
# path=/var/netdisk/admin/root
# pathname=/var/netdisk/admin/root/dd
# src_pathname=/var/netdisk/admin/root/cc
# wd=5 >

print("process_IN_MOVED_TO:", event.pathname)
return

def process_IN_MOVED_FROM(self, event):
# move from
print(event)
# <Event cookie=80916 dir=True
# mask=0x40000040 maskname=IN_MOVED_FROM|IN_ISDIR
# name=aaaa
# path=/var/netdisk/admin/root
# pathname=/var/netdisk/admin/root/aaaa wd=5 >
print("process_IN_MOVED_FROM:", event.pathname)
return


if __name__ == '__main__':
# monitor path
homepath = "/var/netdisk"
# manager
watchManager = pyinotify.WatchManager()
# add homepath to watch
watchManager.add_watch(homepath, pyinotify.ALL_EVENTS, rec=True, rec=False, auto_add=True, do_glob=True)
# create event handler
handler = NetdiskEventHandler()
# notifier
notifier = pyinotify.Notifier(watchManager, handler)
# run loop
notifier.loop()