如何监控远程目录和文件的更改?

2024-04-19 17:18:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图监视远程目录和文件。我需要存储或记录文件和目录的更改,即(访问、写入、打开和关闭事件)。在

我尝试使用pyinotify监视和记录这些事件。我实现了本地系统文件,但我的问题是如何监控远程文件和目录。在

我能在ssh的帮助下实现这一点吗?或者用其他任何可能的方法来记录远程文件和目录中发生的事件?在

我已经给出了本地系统文件监视的代码。在

import pyinotify 
import asyncore 
from .models import AccessEvents 
import threading

class MyEventHandler(pyinotify.ProcessEvent):
    def process_IN_ACCESS(self, event):
        access=AccessEvents(mode_id=1,path=event.pathname)
        access.save()
    def process_IN_ATTRIB(self, event):
        attrib = AccessEvents(mode_id=2, path=event.pathname)
        attrib.save()
    def process_IN_CLOSE_NOWRITE(self, event):
        nwrite = AccessEvents(mode_id=3, path=event.pathname)
        nwrite.save()
    def process_IN_CLOSE_WRITE(self, event):
        write = AccessEvents(mode_id=4, path=event.pathname)
        write.save()
    def process_IN_CREATE(self, event):
        create = AccessEvents(mode_id=5, path=event.pathname)
        create.save()
    def process_IN_DELETE(self, event):
        delete = AccessEvents(mode_id=6, path=event.pathname)
        delete.save()
    def process_IN_MODIFY(self, event):
        modify = AccessEvents(mode_id=7, path=event.pathname)
        modify.save()
    def process_IN_OPEN(self, event):
        open = AccessEvents(mode_id=8, path=event.pathname)
        open.save()

def startmonitor(file_or_dir):
    # watch manager
    wm = pyinotify.WatchManager()
    try:
        test=wm.add_watch(file_or_dir, pyinotify.ALL_EVENTS, rec=True)
        if test[file_or_dir]==-1:
            return 'no_such_file_or_dir'
        else:
            # event handler
            eh = MyEventHandler()
            # notifier
            notifier = pyinotify.AsyncNotifier(wm, eh)
            thread = threading.Thread(target=asyncore.loop(), args=())
            thread.daemon = True  # Daemonize thread
            thread.start()  # Start the execution
            return 'file_monitoring_started'
    except Exception as e:
        print 'error',e

startmonitor('/tmp/test')

如果有人知道远程系统文件监视,请给我你的建议。提前谢谢!!!在


Tags: pathinself目录eventid远程mode
1条回答
网友
1楼 · 发布于 2024-04-19 17:18:58

这可以通过简单的客户机-服务器模型(http)来实现。在

第一步是应该在要监视的远程系统上运行文件监视程序代码。以结构化格式保存更改。例如某物比如:在

class ChangeEvent:

 def __init__(self, event_name)

 def files_changed(self, list_files)

将这些ChangeEvents列表存储为一个队列(充当缓冲区)。制作一个简单的getapi,这样客户机就可以获得这些更改事件的列表。从已发送的队列中删除ChangeEvents。在

现在在客户端应用程序上(可能是它的移动或网络,不重要), 只需定期点击api(您已经在上面做过了)来获得更改。在

您还可以将这些ChangeEvents保存为远程服务器上的json或csv,用于持久存储。在

相关问题 更多 >