码迷,mamicode.com
首页 > 编程语言 > 详细

Python Inotify 监视LINUX文件系统事件

时间:2020-01-18 16:55:15      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:body   -bash   lang   主页   cep   tmp   monit   image   linux   

Inotify 可以监视的LINUX文件系统事件包括:

 --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) 

github主页:https://github.com/seb-m/pyinotify/wiki/Events-types

安装 pyinotify:

# pip install pyinotify

它会从默认仓库安装可用的版本,如果你想要最新的稳定版,可以按如下从 git 仓库 clone 下来:

# git clone https://github.com/seb-m/pyinotify.git
# cd pyinotify/
# ls
# python setup.py install

如何在 Linux 中使用 pyinotify

技术图片
#coding:utf8
#author:lcamry

import os
import pyinotify
from functions import *
 
WATCH_PATH = ‘‘ #监控目录
 
if not WATCH_PATH:
  wlog(‘Error‘,"The WATCH_PATH setting MUST be set.")
  sys.exit()
else:
  if os.path.exists(WATCH_PATH):
    wlog(‘Watch status‘,‘Found watch path: path=%s.‘ % (WATCH_PATH))
  else:
    wlog(‘Error‘,‘The watch path NOT exists, watching stop now: path=%s.‘ % (WATCH_PATH))
    sys.exit()
 
class OnIOHandler(pyinotify.ProcessEvent):
  def process_IN_CREATE(self, event):
    wlog(‘Action‘,"create file: %s " % os.path.join(event.path,event.name))
 
  def process_IN_DELETE(self, event):
    wlog(‘Action‘,"delete file: %s " % os.path.join(event.path,event.name))
 
  def process_IN_MODIFY(self, event):
    wlog(‘Action‘,"modify file: %s " % os.path.join(event.path,event.name))
 
def auto_compile(path = ‘.‘):
  wm = pyinotify.WatchManager()
  mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY
  notifier = pyinotify.ThreadedNotifier(wm, OnIOHandler())
  notifier.start()
  wm.add_watch(path, mask,rec = True,auto_add = True)
  wlog(‘Start Watch‘,‘Start monitoring %s‘ % path)
  while True:
    try:
      notifier.process_events()
      if notifier.check_events():
        notifier.read_events()
    except KeyboardInterrupt:
      notifier.stop()
      break
 
if __name__ == "__main__":
   auto_compile(WATCH_PATH)
技术图片

更多例子见:https://www.cnblogs.com/hollyspirit/p/3182828.html

在下面的例子中,我以 root 用户(通过 ssh 登录)监视了用户 tecmint 的家目录(/home/tecmint)下的改变,如截图所示:

# python -m pyinotify -v /home/tecmint

技术图片

接下来,我会观察到任何 web 目录 (/var/www/html/) 的更改:

# python -m pyinotify -v /var/www/html/tecmint.com

要退出程序,只要按下 Ctrl+C。

注意:当你在运行 pyinotify 时如果没有指定要监视的目录,/tmp 将作为默认目录。

Python Inotify 监视LINUX文件系统事件

标签:body   -bash   lang   主页   cep   tmp   monit   image   linux   

原文地址:https://www.cnblogs.com/qiumingcheng/p/12209156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!