1. 程式人生 > >shell實現篩選Nginx訪問日誌超多閾值郵件告警

shell實現篩選Nginx訪問日誌超多閾值郵件告警

指令碼思路:

1.統計一個小時內ip前十的訪問日誌,擷取前10個;

2.判斷ip訪問的次數,大於1000輸出到臨時檔案中

3.郵件告警;

詳細程式碼如下:

#!/bin/bash
#function:analysis the nginx log file and count spider user
#author:[email protected]
#date:2017-08-28
log=/tmp/illegal.log
>$log
logfile=/usr/local/nginx/logs/access.log
hourtime=`date +%Y:%H`
grep "${hourtime}" $logfile> /tmp/${hourtime}.log
cd /tmp
awk '{print $1}' ${hourtime}.log |sort |uniq -c|sort -nr|head >head_ip.log
for ((i=1; i<=10; i ++))
do
    ip_count[$i]=`sed -n "$i,1p" /tmp/head_ip.log|awk '{print $1}'`
    ip_list[$i]=`sed -n "$i,1p" head_ip.log|awk '{print $2}'`
    #echo "${ip_count[$i]}"
    if [ "${ip_count[$i]}" -gt 1000 ];then
      echo -e "the ${ip_list[$i]} is Illegal ip ,count is ${ip_count[$i]}" >>$log
   fi
   # done
done
if [ -s "$log" ];then
     mail -s "Ip訪問數超過閾值,請注意!!" 
[email protected]
<$log fi