本次需求:监控linux服务器文件变化情况,主要是短时间内大量删除文件的异常情况。
1.inotify-tools安装配置
2.shell脚本编写
#!/bin/sh
time_last="" #上一分钟
delete_time=0 #删除次数
log="" #每分钟日志
#/inotify-logs/test 监控文件
/usr/local/inotify/bin/inotifywait -mrq --timefmt '%y/%m/%d %H:%M' --format '%T %w%f %e' --event delete /inotify-logs/test | while read date time file event
do
case $event in
DELETE|DELETE,ISDIR) #只判断删除
if [ "$(date "+%Y%m%d%H%M")" != "$time_last" ] #是否为上一分钟
then
time_last=$(date "+%Y%m%d%H%M") #更新为本次分钟
delete_time=0
else
delete_time=`expr $delete_time + 1`
if [-z "$log"]
then
log="$event'-'$file'-'$date'-'$time"
else
log="$log\n$event'-'$file'-'$date'-'$time"
fi
if [ $delete_time -gt 100 ] #1分钟内删除文件数大于100
then
echo $log >> /inotify-logs/$(date +%Y)$(date +%m)$(date +%d).log #写入以日期为名的日志
log=""
fi
fi
;;
esac
done
3.nohup 后台执行
sudo chmod -R 777 /root/inotify-logs/web_watch.sh #赋予权限
nohup /root/inotify-logs/web_watch.sh > /root/inotify-logs/watch.log 2>&1 & #执行