在CentOS系统中,监控目录(如/var/www/html)的文件变化并设置告警策略,可以通过多种方式实现。以下是一些常见的方法:
inotifywait工具inotifywait是inotify-tools包中的一个工具,可以实时监控文件系统事件。
inotify-toolssudo 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是一个强大的审计工具,可以监控文件系统的变化。
auditdsudo 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
auditdsudo 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功能强大,适合需要详细审计日志的场景;第三方监控工具则提供了更丰富的监控和告警功能。