Linux文件系統監控方法
inotify是Linux內核提供的文件系統事件監控機制,可實時捕獲文件/目錄的創建、刪除、修改等事件,是Linux下最常用的實時監控方案。
inotify-tools(包含inotifywait和inotifywatch命令)。sudo apt-get install inotify-toolssudo yum install inotify-toolsinotifywait -m /path/to/directoryinotifywait -m -e create,delete,modify /path/to/directoryinotifywait -m -r /path/to/directoryinotifywatch -v -e modify,create,delete -t 60 /path/to/directoryfswatch是一個跨平臺的文件系統監控工具,支持Linux、macOS、Windows等,功能強大且易于使用。
sudo apt-get install fswatchsudo yum install fswatchsudo dnf install fswatchfswatch -r /path/to/directoryfswatch -0 /path/to/directory | while read -d '' event; do echo "Changed: $event"; doneauditd是Linux內核的審計系統,可詳細記錄文件訪問、修改、刪除等操作,適合安全審計和合規性檢查。
sudo apt-get install auditd audispd-pluginssudo yum install auditecho "watch /path/to/directory -p wa -k my_dir_watch" | sudo tee -a /etc/audit/audit.rulessudo systemctl restart auditdausearch -k my_dir_watch輪詢監控通過定時掃描文件狀態(如修改時間、大?。﹣頇z測變化,無需內核支持,但實時性差、資源占用高。
watch -n 1 'ls -l /path/to/directory'#!/bin/bash
original_md5=$(md5sum /path/to/file)
while true; do
current_md5=$(md5sum /path/to/file)
if [ "$original_md5" != "$current_md5" ]; then
echo "File modified!"
original_md5=$current_md5
fi
sleep 5
done
watchdog是基于Python的文件系統監控庫,支持實時監控和自定義事件處理,適合需要復雜邏輯的場景(如文件變化后觸發數據處理)。
pip install watchdogimport time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f"File modified: {event.src_path}")
def on_created(self, event):
print(f"File created: {event.src_path}")
def on_deleted(self, event):
print(f"File deleted: {event.src_path}")
if __name__ == "__main__":
path = "/path/to/directory"
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
若需要監控整個文件系統的狀態(如磁盤空間、inode使用率),可使用可視化工具,它們提供圖形化界面和實時數據展示。
glances。http://localhost:19999查看。