在日常營運中會發現流量突增現象或者伺服器負載升高等現象,為找到原因,需要使用nginx limit模組 對訪問的Ip進行限制,然後可以分析日誌。
配置nginx限制IP訪問,可配置多個zone。
limit_req_zone $binary_remote_addr zone=allips:10m rate=20r/s;
對產生的nginx日誌進行分析 指令碼。
##提供預設日誌路徑和名稱
logsFile="日誌名稱"
##配置多個zoneName
zoneName="allips name2 name3"
##生產臨時檔案存放目錄
mkdir ./cache$$
##日誌分析函數
fenxi(){
for zone in $zoneName;
do
printf "\n當前報告是{ $zone }限制產生的:\n"
grep "$zone" $logFile > ./cache$$/$zone.log
printf "%-7s|%-12s|%-19s|%-20s|%-36s|%s\n" "序號" "次數" "IP地址" "IP歸屬" "時間範圍"
ucount=0;
##過濾出訪問的IP地址並排序去重,保證結果是由訪問次數高到低排序
ip_list=$(egrep -o "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" cache$$/$zone.log |sort |uniq -c |sort -n -r |awk '{print $2}')
for ip in $ip_list;
do
grep $ip cache$$/$zone.log > ./cache$$/temp.$$.log
tstart=`cut -c-19 ./cache$$/temp.$$.log | head -1`
tend=`cut -c-19 ./cache$$/temp.$$.log|tail -1`
let ucount++
Attempts=`cat ./cache$$/temp.$$.log |wc -l`
time_range="$tstart"--"$tend"
##通過138找到ip地址歸屬
ip138=`curl -s "http://ip138.com/ips138.asp?ip=$ip&action=2"| iconv -f gb2312 -t utf-8 |grep '' | awk -F '[<> ]+' '{print substr($7,6)}'`
ipwhere=`echo $ip138 |awk '{print $7}'`
printf "%-5s|%-10s|%-17s|%-20s|%-33s|%s\n" "$ucount" "$Attempts" "$ip" "$ipwhere" "$time_range"
done
done
}
##可以手動輸入記錄檔或者執行預設分析
if [ "$1" = "" ];then
for logFile in $logsFile;
do
if [ -f "$logFile" ]
then
printf "\n#############################################################\n"
printf "\n當前分析的記錄檔: $logFile ,以下是產生的報告:\n"
else
echo "記錄檔出錯,請檢查檔案"
fi
echo "當前日誌分析時間: `date`"
fenxi
done
else
logFile=$1
printf "\n################################################################\n"
printf "\n當前分析的記錄檔: $logFile ,以下是產生的報告:\n"
echo "當前日誌分析時間: `date`"
fenxi
fi
rm -rf cache$$/