• Python的看门狗实现自动化实时对服务器、Windows或Linux文件夹的实时监控


    众所周知,在运维过程中,实时获取目标文件夹至关重要,Python的watchdog是用程序来监视文件系统事件Python库,所以用该库可以实现对文件夹的实时监控,filenotify.py代码如下:

    # -*- coding: utf-8 -*-
    #!/usr/bin/env python 
    # @Time    : 2018/2/8 17:48
    # @Desc    : 监控工作目录文件夹
    # @File    : filenotify.py
    # @Software: PyCharm
    
    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()
        #Windows
        observer.schedule(event_handler, "D:", True)
        #Linux、服务器
        # observer.schedule(event_handler,"/home/../",True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
        observer.join() 

    监控结果如下:

    安装watchdog命令  pip install watchdog

  • 相关阅读:
    设计模式:迭代器模式(Iterator Pattern) 明
    设计模式:目录导航 明
    设计模式:状态模式(State Pattern) 明
    设计模式:命令模式(Command Pattern) 明
    二维DP—— POJ 3186
    COM组件里自动化接口与普通接口的转换
    贪心好题——poj3044
    三分查找——POJ3301
    静态链表+DFS——poj 3272
    妙用队列优化——校赛题
  • 原文地址:https://www.cnblogs.com/IT-LearnHall/p/9426242.html
Copyright © 2020-2023  润新知