Linux下使用inotify-tools实现文件监控并自动推送钉钉webhook告警
原文:https://cloud.tencent.com/developer/article/2427949?policyId=1004
1、安装 inotify-tools
yum install inotify-tools -y
2、编写 file_monitor.sh
#!/bin/bash
# 钉钉机器人webhook地址
DINGTALK_WEBHOOK="https://oapi.dingtalk.com/robot/send?access_token=838eb303c4035b35447b3caaaa486b2ee6b1f4918be28eba07f7b491155652bc"
# 要监控的目录路径
WATCH_DIR="/opt/"
# 事件列表(包括 create、modify、delete)
EVENTS="create,modify,delete"
# 函数:发送消息到钉钉
send_to_dingtalk() {
local message=$1
curl -s -X POST $DINGTALK_WEBHOOK \
-H 'Content-Type: application/json' \
-d "{
\"msgtype\": \"markdown\",
\"markdown\": {
\"title\":\"文件变化告警\",
\"text\":\"$message\"
}
}"
}
# 获取主机名和IP
HOSTNAME=$(hostname)
IP=$(hostname -I)
# 运行 inotifywait 并处理事件循环
inotifywait -m -r --format '%w%f %e' --event $EVENTS $WATCH_DIR | while read file event; do
CURRENT_TIME=$(date +"%Y-%m-%d %H:%M:%S")
EVENT_MESSAGE="
##### 文件变化告警 \n
> ##### <font color=#67C23A> 【项目名称】: </font> <font color=#FF0000>xx项目</font> \n
> ##### <font color=#67C23A> 【服务器名称】: </font> <font color=#FF0000>$HOSTNAME</font> \n
> ##### <font color=#67C23A> 【服务器IP】:</font><font color=#FF0000>$IP</font>\n
> ##### <font color=#67C23A> 【告警时间】:</font><font color=#FF0000>$CURRENT_TIME</font>\n
> ##### <font color=#67C23A> 【事件详情】:</font>\n
>- 发生变化的文件:<code>${file}</code>\n
>- inotify事件类型:<font color=#FF0000> <code>${event}</code> </font>
"
echo "$EVENT_MESSAGE" # 输出事件信息(可选)
send_to_dingtalk "$EVENT_MESSAGE" # 调用函数以通知到 dingding webhook
done
并将脚本拷贝到 /usr/local/bin
目录下,添加执行权限
cp file_monitor.sh /usr/local/bin/file_monitor.sh
chmod 777 /usr/local/bin/file_monitor.sh
3、编写 systemctl 服务文件
vim /etc/systemd/system/file-monitor.service
添加如下内容
[Unit]
Description=File Monitor Service for Directory Changes Notification via DingTalk
[Service]
Type=simple
ExecStart=/usr/local/bin/file_monitor.sh
# Restart service on failure to ensure it keeps running.
Restart=on-failure
RestartSec=5s
# Environment variables can be set here if needed.
# Example:
# Environment="VAR_NAME=value"
[Install]
WantedBy=multi-user.target
4、启动服务
systemctl daemon-reload
systemctl enable --now file-monitor.service
systemctl status file-monitor.service
5、测试验证告警效果
要监控的目录/opt/下创建一个测试文件
[root@almalinux ~]# touch /opt/test.txt
[root@almalinux ~]# echo 123 > /opt/test.txt
[root@almalinux ~]# rm -rf /opt/test.txt
[root@almalinux ~]#
作者:Jeebiz 创建时间:2025-03-26 09:30
最后编辑:Jeebiz 更新时间:2025-03-28 15:38
最后编辑:Jeebiz 更新时间:2025-03-28 15:38