https://github.com/seb-m/pyinotify

在线安装pyinotify:

  1. # pip install pyinotify

它将从默认存储库安装可用版本。

离线安装或者git仓库获取最新包

pyinotify-master.zip

  1. # git clone https://github.com/seb-m/pyinotify.git
  2. # cd pyinotify/
  3. # ls
  4. # pythonXXX setup.py install

在Linux中使用pyinotify

  1. # python -m pyinotify -v /目录

监控目录更改

接下来,我们会随时关注Web目录( /var/www/html/debian.cn )的任何更改:

  1. # pythonXXX -m pyinotify -v /var/www/html/

Python脚本

复制以下保存为 .py文件

  1. import pyinotify
  2. class MyEventHandler(pyinotify.ProcessEvent):
  3. def process_IN_ACCESS(self, event):
  4. """
  5. 文件被访问
  6. :param event:
  7. :return:
  8. """
  9. print("件被访问: ", event.pathname)
  10. def process_IN_ATTRIB(self, event):
  11. """
  12. 文件属性被修改,如chmod、chown、touch等
  13. :param event:
  14. :return:
  15. """
  16. print("文件属性被修改:", event.pathname)
  17. def process_IN_CLOSE_NOWRITE(self, event):
  18. """
  19. 不可写文件被close
  20. :param event:
  21. :return:
  22. """
  23. print("不可写文件被close event:", event.pathname)
  24. def process_IN_CLOSE_WRITE(self, event):
  25. """
  26. 可写文件被close
  27. :param event:
  28. :return: rsync -av /etc/passwd 192.168.204.168:/tmp/passwd.txt
  29. """
  30. print("可写文件被close:", event.pathname)
  31. def process_IN_CREATE(self, event):
  32. """
  33. 创建新文件
  34. :param event:
  35. :return:
  36. """
  37. print("创建新文件:", event.pathname)
  38. def process_IN_DELETE(self, event):
  39. """
  40. 文件被删除
  41. :param event:
  42. :return:
  43. """
  44. print("文件被删除:", event.pathname)
  45. def process_IN_MODIFY(self, event):
  46. """
  47. 文件被修改
  48. :param event:
  49. :return:
  50. """
  51. print("文件被修改:", event.pathname)
  52. def process_IN_OPEN(self, event):
  53. """
  54. 文件被打开
  55. :param event:
  56. :return:
  57. """
  58. print("OPEN event:", event.pathname)
  59. if __name__ == '__main__':
  60. monitor_obj = pyinotify.WatchManager()
  61. # path监控的目录
  62. monitor_obj.add_watch(path, pyinotify.ALL_EVENTS, rec=True)
  63. # event handler
  64. event_handler= MyEventHandler()
  65. # notifier
  66. monitor_loop= pyinotify.Notifier(monitor_obj, event_handler)
  67. monitor_loop.loop()

运行

  1. python3 脚本名称