linux中Shell分析Nginx日誌 找出被阻止的IP

來源:互聯網
上載者:User

在日常營運中會發現流量突增現象或者伺服器負載升高等現象,為找到原因,需要使用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$$/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.