美文网首页
应急响应中的文件改动监控-windows

应急响应中的文件改动监控-windows

作者: 大仲的书屋 | 来源:发表于2019-03-22 20:56 被阅读0次

    windows下文件监控用的是windows 的API FindFirstChangeNotification与FindNextChangeNotification来监控文件变化信号,直接只用C调用他们的话有点麻烦,不过现在有已经封装好的py包watchdog,通过结合syslog将变动日志发送到日志服务器,可以实现文件变动监控。watchdog 使用方法可以参考搜索引擎。

    #coding:utf8
    import logging
    import zlib
    import base64
    import logging.handlers
    import socket
    from logging.handlers import SysLogHandler
    import sys
    import time
    import logging
    from watchdog.observers import Observer
    from watchdog.events import LoggingEventHandler
    from watchdog.events import PatternMatchingEventHandler
    log = logging.getLogger(__name__)
    log.setLevel(logging.DEBUG)
    handler = logging.handlers.SysLogHandler(address=('Your Server Ip', 514), facility=SysLogHandler.LOG_USER, socktype=socket.SOCK_DGRAM)
    formatter = logging.Formatter('%(module)s.%(funcName)s: %(message)s')
    handler.setFormatter(formatter)
    log.addHandler(handler)
    
    
    class fileHandler(PatternMatchingEventHandler):
        def __init__(self): 
            super(fileHandler,self).__init__(patterns=["*.*","*.py","*.txt"])
        def on_moved(self,event):
            self.mylog("moved:"+event.src_path+","+event.dest_path)
            print "moved",event.src_path,event.dest_path
    
        def on_created(self,event):
            self.mylog("created:"+event.src_path)
            print "created",event.src_path
        def on_deleted(self,event):
            self.mylog("deleted:"+event.src_path)
            print "deleted",event.src_path
        def on_modified(self,event):
            self.mylog("modified"+event.src_path)
            print "modified",event.src_path
        def mylog(self,obj):
            log.debug("hello:"+(obj))
    if __name__ == "__main__":
        path = sys.argv[1] if len(sys.argv) > 1 else '.'
        event_handler = fileHandler()
        observer = Observer()
        observer.schedule(event_handler, "H:\\", recursive=True)
        observer.schedule(event_handler, "c:\\", recursive=True)
        observer.schedule(event_handler, "d:\\", recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()
    

    这个代码监控 windows的 H,C ,D盘的文件变动,并把变动结果发送到日志服务器上,可以修改文件里的patterns参数来决定监控那种扩展名的文件。这个脚本同样适用于linux。

    相关文章

      网友评论

          本文标题:应急响应中的文件改动监控-windows

          本文链接:https://www.haomeiwen.com/subject/xhldvqtx.html