分类: LINUX
2016-08-18 12:08:40
#!/bin/sh ##Author:bbzsxjj ##Email:bbzsxjj@163.com ##Usage:auto deny ip by iptables ##Ver:1.0 timenow=`date +'%H%M00'` timelast=`date +'%H%M00' -d '-5min'` lastnum=1000000 ##日志的行数,可以根据自己的业务频率选取 limitnum=3000 ##并发限制,300*10 ipbin=/sbin/iptables NeedDenyiplist=/opt/sbin/ipdeny.list NeedPurgeiplist=/opt/sbin/ippurge.list LogFile=/data/logs/haproxy.log CreateList(){ if [ -f ${LogFile} ] then if [ -f ${NeedDenyiplist} ] then mv ${NeedDenyiplist} ${NeedPurgeiplist} fi tail -n${lastnum} ${LogFile}|awk '{gsub(/:/,"",$3);if($3>='${timelast}' && $3<='${timenow}'){a[$6]++}}END{for(i in a){if(a[i]>'${limitnum}'){print $6}}}' >>${NeedDenyiplist} ##这里需要根据日志的格式进行处理,具体的需要根据实际情况修改处理方法 if [ `wc -l ${NeedDenyiplist}|awk '{print $1}'` -eq 0 ] then rm -rf ${NeedDenyiplist} fi fi } DenyIP(){ for Dip in `cat ${NeedDenyiplist}|grep -E -v '^$|#'` do ${ipbin} -I INPUT -s ${Dip} -p tcp --dport 80 -j DROP done } PurgeIP(){ for Dip in `cat ${NeedPurgeiplist}|grep -E -v '^$|#'` do ${ipbin} -D INPUT -s ${Dip} -p tcp --dport 80 -j DROP done } main(){ CreateList if [ -f ${NeedPurgeiplist} ] then PurgeIP fi if [ -f ${NeedDenyiplist} ] then DenyIP fi } main |