在Ubuntu系統中,使用inotify可以實現多用戶共享監控文件或目錄的變化。以下是實現多用戶共享監控的步驟:
首先,確保你已經安裝了inotify-tools
,這是一個常用的inotify工具集。
sudo apt-get update
sudo apt-get install inotify-tools
創建一個腳本文件,例如monitor.sh
,并添加以下內容:
#!/bin/bash
# 監控的目錄
MONITOR_DIR="/path/to/your/directory"
# 用戶列表文件
USER_LIST="/path/to/user_list.txt"
# 讀取用戶列表并發送通知
while read -r user; do
# 使用wall命令向指定用戶發送通知
wall "File system change detected in $MONITOR_DIR by $USER"
done < "$USER_LIST"
# 使用inotifywait監控目錄變化
inotifywait -m -r -e create,delete,modify --format '%w%f' "$MONITOR_DIR" | while read FILE; do
# 當檢測到文件變化時,重新讀取用戶列表并發送通知
while read -r user; do
wall "File system change detected in $MONITOR_DIR by $USER: $FILE"
done < "$USER_LIST"
done
創建一個文本文件user_list.txt
,并在其中列出所有需要接收通知的用戶。每行一個用戶名。
user1
user2
user3
確保腳本具有執行權限:
chmod +x monitor.sh
以root用戶身份運行腳本,以確保它可以訪問所有用戶的終端并發送通知。
sudo ./monitor.sh
為了使監控腳本在系統啟動時自動運行,可以將其配置為一個systemd服務。
創建一個新的服務文件,例如/etc/systemd/system/monitor.service
,并添加以下內容:
[Unit]
Description=File system change monitor
After=network.target
[Service]
ExecStart=/path/to/monitor.sh
Restart=always
User=root
[Install]
WantedBy=multi-user.target
啟用并啟動服務:
sudo systemctl enable monitor.service
sudo systemctl start monitor.service
wall
命令會將通知發送到所有用戶的終端。如果用戶不在終端上,他們將不會收到通知??梢钥紤]使用其他通知方式,如郵件或Slack。通過以上步驟,你可以在Ubuntu系統中實現多用戶共享監控文件或目錄的變化。