1、Shell脚本监控Nginx access 404报警
#!/bin/bash
logfile=/root/shell/ip_log.txt
access_log=/usr/local/nginx/logs/access.log
#开始时间5分钟前
start_time=`date -d"5 minutes ago" +"%d/%b/%Y:%H:%M:%S"`
#结束时间
end_time=`date +"%d/%b/%Y:%H:%M:%S"`
#查询时间段内的访问日志,统计出访问IP及其访问次数
tac $access_log | grep "HTTP/1.1\" 404" | awk -v st="$start_time" -v et="$end_time" '{t=substr($4,RSTART+2,21);if(t>st && t<=et) {print $0}}' | awk '{print $1}' | sort | uniq -c | sort -nr > $logfile
#逐行读取
cat $logfile | while read LINE
do
LINE=${LINE%%} #去首尾空格
#空格分割取次数和IP
access_count=`echo $LINE | cut -d ' ' -f 1`
access_ip=`echo $LINE | cut -d ' ' -f 2`
if [[ $access_count -gt 30 ]];then
#echo $access_count
#echo $access_ip
#钉钉报警
content="【$access_ip】访问次数【$access_count】"
curl 'https://oapi.dingtalk.com/robot/send?access_token=4be17d56d39ccc4ceddbe45737ff036719b4bd4a0e8b96d0dda0f7460497ae50' -H 'Content-Type: application/json' -d '{"msgtype":"text","text":{"content":"'$content'"}}'
fi
done