web 防攻击shell脚本

统计nginx日志,当单个ip在10秒钟内访问 /account/sendPhoneCode次数超过5次,就禁用这个ip,正常用户不可能有么大的访问量

#!/bin/bash
#write: lijing QQ 858080796
#date:  20160528 v2.0
#description:拦截非法IP
   
#定义变量
RETVAL=0
Date=$(date '+%Y-%m-%d')
Time=$(date '+%Y:%H:%M' -d '-1 minute')
MON=$(date|awk -F" " '{print $2}')
TODAY=$(date|awk -F" " '{print $3}')
Log="/data/logs/nginx/access.log "
LINE="70000"
   
#关键字
Key01="sendPhoneCode"
   
Status=/tmp/statuS_deny_ip
   
/sbin/service iptables status > $Status
   
#定义函数
#禁止时间函数
secure_deny_time(){
Time01=$(date "+%H:%M:%S" -d " -10 second")
Time02=$(date "+%H:%M:%S" -d " -9  second")
Time03=$(date "+%H:%M:%S" -d " -8  second")
Time04=$(date "+%H:%M:%S" -d " -7  second")
Time05=$(date "+%H:%M:%S" -d " -6  second")
Time06=$(date "+%H:%M:%S" -d " -5  second")
Time07=$(date "+%H:%M:%S" -d " -4  second")
Time08=$(date "+%H:%M:%S" -d " -3  second")
Time09=$(date "+%H:%M:%S" -d " -2  second")
Time10=$(date "+%H:%M:%S" -d " -1  second")
    echo  "$Time01  $Time02 $Time03 $Time04 $Time05 $Time06 $Time07 $Time08 $Time09 $Time10 "
}
#       禁止关键字函数
secure_key(){
    tail -n $LINE $LOG |grep "$TODAY\/$MON"|grep -v ^$|grep $TIME|grep $1 |grep $2 |grep $3  |grep $4 |awk -F " " '{print $1}' |sort >> $Deny
    echo " grep "$TODAY\/$MON" $LOG |grep -v ^$|grep $TIME|grep $1 |grep $2 |grep $3  |grep $4 |awk '{print $1}' |sort"
        }
#执行防火墙拦截函数
secure_deny_ip()
{
        cat $Deny
        echo ......................
        cat $Deny02
    for i in $IP;do
        NUM=$(cat $Deny02|grep $i|awk -F" " '{print $1}')
       if [ -z $NUM ];then
            echo " "
        else
            if [ $NUM -ge $Dot ];then
                for y in $i;do
                    grep $y $Status  >/dev/null 2>&1 
                    RETVAL=$?
                                        [ $RETVAL != 0  ] && echo "/sbin/iptables -I INPUT -s $y  -j DROP"
[ $RETVAL != 0  ] && /sbin/iptables -I INPUT -s $y  -j DROP 
                                        [ $RETVAL != 0  ] && echo "$(date "+%H:%M:%S") $y " >> /tmp/$Date
                    #[ $RETVAL != 0  ] && /sbin/iptables -I INPUT -s $y -p  tcp  -j REJECT
                done
            fi
        fi
    done
}
   
   
NUMBER="1 2 3 4 5 6"
for  NUMBER in  $NUMBER   ;do
sleep 10s
#定义点击次数 Dot
Dot=5
Deny=/tmp/secure_deny_tmp_$NUMBER
Deny02=/tmp/secure_deny_$NUMBER
#第1次,检查当前时间以前10s.  如: 0-10秒
echo "第$NUMBER 次,检查当前时间以前第$NUMBER 个10s.大于 $Dot 次攻击阻止"
echo > $Deny
for LOG in `echo $Log` ;do
    secure_deny_time
    for TIME in $Time01  $Time02 $Time03 $Time04 $Time05 $Time06 $Time07 $Time08 $Time09 $Time10 ;do
        secure_key  $Key01 
    done
       cat $Deny|sort|uniq -c > $Deny02         
   IP=$(cat $Deny02|awk -F" " '{print $2}')
        secure_deny_ip 
done
done
exit
posted @ 2016-10-16 09:06  幻月0412  阅读(194)  评论(0编辑  收藏  举报