2017-09-13 164 views
-1

我想監視遠程目錄和文件。我需要存儲或記錄文件和目錄的更改(訪問,寫入,打開和關閉事件)。如何監視遠程目錄和文件的更改?

我試着用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') 

如果有人知道遠程系統文件監控,請向我提供您的建議。提前致謝!!!

回答

1

它可以用簡單的客戶端 - 服務器模型(http)來完成。

第一步是您應該在您要觀看的遠程系統上運行文件觀察程序代碼。保持更改結構化的格式。例如: -

class ChangeEvent: 

def __init__(self, event_name) 

def files_changed(self, list_files) 

將這些ChangeEvents列表存儲爲一個隊列(充當緩衝區)。製作一個簡單的GET API,以便客戶端可以獲取這些更改事件的列表。從您發送的隊列中刪除ChangeEvents。

現在在客戶端應用程序(也許它的手機或網絡,無所謂), 只需定期(你已經做出了上述)的api來獲取更改。

您還可以將這些ChangeEvents另存爲遠程服務器上的json或csv,以用於永久存儲。