在CentOS系統中,監控目錄(如/var/www/html
)的文件變化并設置告警策略,可以通過多種方式實現。以下是一些常見的方法:
inotifywait
工具inotifywait
是inotify-tools
包中的一個工具,可以實時監控文件系統事件。
inotify-tools
sudo yum install inotify-tools -y
創建一個腳本monitor.sh
:
#!/bin/bash
MONITOR_DIR="/var/www/html"
LOG_FILE="/var/log/inotify_monitor.log"
# 監控目錄變化并記錄到日志
inotifywait -m -r -e create,delete,modify --format '%w%f %e' "$MONITOR_DIR" >> "$LOG_FILE" 2>&1 &
# 檢查inotifywait進程是否運行
if [ $? -ne 0 ]; then
echo "Failed to start inotifywait."
exit 1
fi
# 可以在這里添加告警邏輯,例如發送郵件或執行其他命令
使用cron
定期檢查日志文件并發送告警:
crontab -e
添加以下內容:
* * * * * /path/to/monitor.sh
auditd
進行審計auditd
是一個強大的審計工具,可以監控文件系統的變化。
auditd
sudo yum install audit -y
auditd
編輯/etc/audit/auditd.conf
文件,確保以下配置:
log_format = RAW
write_logs = yes
創建一個審計規則文件/etc/audit/rules.d/monitor.rules
:
-a always,exit -F path=/var/www/html -F perm=wa -k monitor_dir
auditd
sudo systemctl start auditd
sudo systemctl enable auditd
ausearch -k monitor_dir
可以使用第三方監控工具如Prometheus、Grafana等來監控文件系統的變化。
sudo yum install prometheus grafana -y
編輯/etc/prometheus/prometheus.yml
文件,添加節點 exporter 和文件系統監控:
scrape_configs:
- job_name: 'node'
static_configs:
- targets: ['localhost:9100']
- job_name: 'filesystem'
static_configs:
- targets: ['localhost:9101']
sudo systemctl start prometheus
sudo systemctl start grafana-server
在Grafana中添加Prometheus數據源,并創建儀表盤來監控文件系統的變化。
以上方法各有優缺點,可以根據具體需求選擇合適的方法。inotifywait
簡單易用,適合小型項目;auditd
功能強大,適合需要詳細審計日志的場景;第三方監控工具則提供了更豐富的監控和告警功能。