inotify
是 Linux 內核提供的一種文件系統事件監控機制,它可以實時監控文件或目錄的變化,如創建、刪除、修改等。在 Debian 上配置 inotify
通常涉及以下幾個步驟:
首先,確保你的系統上安裝了 inotify-tools
,這是一個常用的 inotify
工具集。
sudo apt update
sudo apt install inotify-tools
inotifywait
監控文件或目錄inotifywait
是 inotify-tools
中的一個命令行工具,可以用來監控文件或目錄的變化。
inotifywait -m /path/to/directory -e create,delete,modify
-m
:持續監控模式。/path/to/directory
:要監控的目錄路徑。-e
:指定要監控的事件類型,如 create
、delete
、modify
等。假設你想監控 /home/user/documents
目錄,并在文件創建、刪除或修改時打印通知:
inotifywait -m /home/user/documents -e create,delete,modify |
while read path action file; do
echo "The file '$file' appeared in directory '$path' via '$action'"
done
如果你希望 inotify
監控在系統啟動時自動運行,可以將其配置為一個 systemd 服務。
創建一個新的 systemd 服務文件,例如 /etc/systemd/system/inotify-monitor.service
:
[Unit]
Description=Inotify Monitor Service
After=network.target
[Service]
ExecStart=/usr/bin/inotifywait -m /path/to/directory -e create,delete,modify |
/bin/bash -c 'while read path action file; do echo "The file '\''$file'\'' appeared in directory '\''$path'\'' via '\''$action'\''"; done'
Restart=always
User=your_username
[Install]
WantedBy=multi-user.target
ExecStart
:指定要運行的命令。Restart=always
:確保服務在退出時自動重啟。User
:指定運行服務的用戶。sudo systemctl daemon-reload
sudo systemctl enable inotify-monitor.service
sudo systemctl start inotify-monitor.service
你可以將 inotifywait
的輸出重定向到一個日志文件,以便后續查看:
inotifywait -m /path/to/directory -e create,delete,modify |
while read path action file; do
echo "$(date): The file '$file' appeared in directory '$path' via '$action'" >> /var/log/inotify.log
done
通過以上步驟,你可以在 Debian 上配置 inotify
來監控文件或目錄的變化。根據你的需求,可以選擇使用命令行工具 inotifywait
或將其配置為 systemd 服務以實現自動監控。