2017年10月9日 星期一

[ Python 文章收集 ] watchdog - 監控文件系統事件的 Python 庫和 shell 工具

Source From Here 
Preface 
watchdog 提供了 Python API 和 shell 工具集來監控文件系統的事件。它包含跨平台的 API,一個 shell 工具可以讓你運行命令來監控目錄的變化。以下是一個使用 watchdog 來監控目錄變化的的簡單程序,當事件發生的時候記錄日誌: 
* Create an instance of the watchdog.observers.Observer thread class.
* Implement a subclass of watchdog.events.FileSystemEventHandler as MyEH (or use the built-in watchdog.events.LoggingEventHandler, which already does).
* Schedule monitoring a few paths with the observer instance attaching the event handler.
* Start the observer thread and wait for it generate events without blocking our main thread.
* If a stop signal being received, stop the observer thread

- wd_t1.py 
  1. #!/usr/bin/env python  
  2. import sys, os  
  3. import time  
  4. import logging  
  5. from watchdog.observers import Observer  
  6. from watchdog.events import LoggingEventHandler  
  7.   
  8. class MyEH(LoggingEventHandler):  
  9.     r''' Logs all the events captured. '''  
  10.     def __init__(self):  
  11.         super(MyEH, self).__init__()  
  12.   
  13.     def on_created(self, event):  
  14.         r'''  
  15.         We only care about the file being created  
  16.         '''  
  17.         super(MyEH, self).on_created(event)  
  18.         print("This event is captured by {}:\n{}\n".format(self.__class__, event))  
  19.   
  20.   
  21. STOP_SIG = 'STOP'  
  22. if __name__ == "__main__":  
  23.     logging.basicConfig(level=logging.INFO,  
  24.                         format='%(asctime)s - %(message)s',  
  25.                         datefmt='%Y-%m-%d %H:%M:%S')  
  26.     path = sys.argv[1if len(sys.argv) > 1 else '.'  
  27.     event_handler = MyEH()  
  28.     observer = Observer()  
  29.     observer.schedule(event_handler, path, recursive=True)  
  30.     observer.start()  
  31.     try:  
  32.         while True:  
  33.             time.sleep(1)  
  34.             if os.path.isfile(STOP_SIG):  
  35.                 print("Receive STOP signal({})...".format(STOP_SIG))  
  36.                 os.remove(STOP_SIG)  
  37.                 observer.stop()  
  38.                 break;  
  39.     except KeyboardInterrupt:  
  40.         observer.stop()  
  41.     observer.join()  
Then you can test it this way: 
# ./wd_t1.py & // Run the program in background by monitoring current working path
[1] 23020
# touch test // Create a new file to trigger event
2017-10-10 13:54:39 - Created file: ./test
This event is captured by :


# touch STOP // Create a stop signal to stop the program
Receive STOP signal(STOP)...
[1]+ Done ./wd_t1.py

watchdog 包含一個實用的腳本,名為 watch demo。使用 watchmedo --help 命令可以查看更多關於這個腳本的信息。 
# which watchmedo
/usr/bin/watchmedo

# watchmedo --help // Check help message
...


以下是一個監控 *.py 和 *.txt 文件的變化,記錄到日誌而忽略其他目錄中文件變化的腳本: 
  1. watchmedo log \  
  2.     --patterns="*.py;*.txt" \  
  3.     --ignore-directories \  
  4.     --recursive \  
  5.     .  
可以使用 shell-command 子命令來執行shell命令: 
  1. watchmedo shell-command \  
  2.     --patterns="*.py;*.txt" \  
  3.     --recursive \  
  4.     --command='echo "${watch_src_path}"' \  
  5.     .  

Supplement 
Watchdog document

沒有留言:

張貼留言

[Linux 文章收集] Linux / Unix: Check Last Time User Logged In On The System

Source From  Here   Question   I am a new Unix system admin. How do I find ouw who has recently use the Linux or Unix-like server?  Which te...