天天看點

3、python檔案變化監控子產品watchdog使用

業務場景:

最近公司要開發雲虛拟機檔案操作平台,其中重要的一步就是記錄出使用者進入該windows虛拟機,對檔案的操作行為。
           
查了一上午資料,在python中檔案監控主要有兩個庫,一個是pyinotify ( https://github.com/seb-m/pyinotify/wiki ),一個是watchdog(http://pythonhosted.org/watchdog/)。pyinotify依賴于Linux平台的inotify,後者則對不同平台的的事件都進行了封裝。因為我主要用于Windows平台,是以下面着重介紹python使用watchdog對檔案及檔案夾變化實時監控,具體細節,以後對在更新文章。下面是一個簡單的demo,修改路徑就可以跑起來。

安裝watchdog:

pip install watchdog
           

代碼實作

from watchdog.observers import Observer
from watchdog.events import *
import time


class FileEventHandler(FileSystemEventHandler):
    def __init__(self):
        FileSystemEventHandler.__init__(self)

    def on_moved(self, event):
        if event.is_directory:
            print("directory moved from {0} to {1}".format(event.src_path, event.dest_path))
        else:
            print("file moved from {0} to {1}".format(event.src_path, event.dest_path))

    def on_created(self, event):
        if event.is_directory:
            print("directory created:{0}".format(event.src_path))
        else:
            print("file created:{0}".format(event.src_path))

    def on_deleted(self, event):
        if event.is_directory:
            print("directory deleted:{0}".format(event.src_path))
        else:
            print("file deleted:{0}".format(event.src_path))

    def on_modified(self, event):
        if event.is_directory:
            print("directory modified:{0}".format(event.src_path))
        else:
            print("file modified:{0}".format(event.src_path))


if __name__ == "__main__":
    observer = Observer()
    event_handler = FileEventHandler()
    observer.schedule(event_handler, r"C:\Users\wyq\Desktop\1", True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

           

運作結果

3、python檔案變化監控子產品watchdog使用