防CC***自動拉黑IP

#!/bin/bash
##取得參數$1爲併發閾值,若留空則默認允許單IP最大50併發(實際測試發現,2M帶寬,十來個併發服務器就已經無法訪問了!)
if [[ -z $1 ]];then
        num=50
else
        num=$1
fi
 
#巧妙的進入到腳本工作目錄
cd $(cd $(dirname $BASH_SOURCE) && pwd)
 
#請求檢查, 判斷及拉黑主功能函數
function check(){
        iplist=`netstat -an |grep ^tcp.*:80|egrep -v 'LISTEN|127.0.0.1'|awk -F"[ ]+|[:]" '{print $6}'|sort|uniq -c|sort -rn|awk -v str=$num '{if ($1>str){print $2}}'`
        if [[ ! -z $iplist ]];
                then
                >./black_ip.txt
                for black_ip in $iplist
                do
                        #白名單過濾中已取消IP段的判斷功能,可根據需要自行修改以下代碼
                        #exclude_ip=`echo $black_ip | awk -F"." '{print $1"."$2"."$3}'`
                        #grep -q $exclude_ip ./white_ip.txt
                        grep -q $black_ip ./white_ip.txt
                        if [[ $? -eq 0 ]];then
                                echo "$black_ip (white_ip)" >>./black_ip.txt
                        else
                                echo $black_ip >>./black_ip.txt     
                                iptables -nL | grep $black_ip ||(iptables -I INPUT -s $black_ip -j DROP & echo "$black_ip  `date +%Y-%m-%H:%M:%S`">>./deny.log & echo 1 >./sendmail)
                        fi
                done
                #存在併發超過閥值的單IP就發送郵件
                if [[ `cat ./sendmail` == 1 ]];then sendmsg;fi
        fi
}
 
#發郵件函數
function sendmsg(){
        netstat -nutlp | grep "sendmail" >/dev/null 2>&1 || /etc/init.d/sendmail start >/dev/null 2>&1
        echo -e "From: [email protected]\nTo:[email protected]\nSubject:Someone Attacking your system!!\nIts Ip is" >./message
        cat ./black_ip.txt >>./message
        /usr/sbin/sendmail -f [email protected] -t [email protected] -i <./message
        >./sendmail
}
 
#
while true
do
        check
        #每隔10s檢查一次,時間可格局需要自定義
        sleep 10
done

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章