https://github.com/seb-m/pyinotify
在线安装pyinotify:
# pip install pyinotify
离线安装或者git仓库获取最新包
# git clone https://github.com/seb-m/pyinotify.git
# cd pyinotify/
# ls
# pythonXXX setup.py install
在Linux中使用pyinotify
# python -m pyinotify -v /目录
监控目录更改
接下来,我们会随时关注Web目录( /var/www/html/debian.cn )的任何更改:
# pythonXXX -m pyinotify -v /var/www/html/
Python脚本
复制以下保存为 .py
文件
import pyinotify
class MyEventHandler(pyinotify.ProcessEvent):
def process_IN_ACCESS(self, event):
"""
文件被访问
:param event:
:return:
"""
print("件被访问: ", event.pathname)
def process_IN_ATTRIB(self, event):
"""
文件属性被修改,如chmod、chown、touch等
:param event:
:return:
"""
print("文件属性被修改:", event.pathname)
def process_IN_CLOSE_NOWRITE(self, event):
"""
不可写文件被close
:param event:
:return:
"""
print("不可写文件被close event:", event.pathname)
def process_IN_CLOSE_WRITE(self, event):
"""
可写文件被close
:param event:
:return: rsync -av /etc/passwd 192.168.204.168:/tmp/passwd.txt
"""
print("可写文件被close:", event.pathname)
def process_IN_CREATE(self, event):
"""
创建新文件
:param event:
:return:
"""
print("创建新文件:", event.pathname)
def process_IN_DELETE(self, event):
"""
文件被删除
:param event:
:return:
"""
print("文件被删除:", event.pathname)
def process_IN_MODIFY(self, event):
"""
文件被修改
:param event:
:return:
"""
print("文件被修改:", event.pathname)
def process_IN_OPEN(self, event):
"""
文件被打开
:param event:
:return:
"""
print("OPEN event:", event.pathname)
if __name__ == '__main__':
monitor_obj = pyinotify.WatchManager()
# path监控的目录
monitor_obj.add_watch(path, pyinotify.ALL_EVENTS, rec=True)
# event handler
event_handler= MyEventHandler()
# notifier
monitor_loop= pyinotify.Notifier(monitor_obj, event_handler)
monitor_loop.loop()
运行
python3 脚本名称