Shell脚本范例(五)——解决DoS攻击

本文分享常用的一些Shell脚本的例子,这是第五篇——解决DoS攻击。

要求:写一个Shell脚本解决类DDoS攻击的生产案例。请根据Web日志或系统连接数,监控某个IP的并发连接数,若短时间内PV达到100,即调用防火墙命令封掉对应的IP(命令为:iptables -I INPUT -s ip -j DROP)。

参考:

#!/bin/bash
#Author: Oliver King
#Blog: http://www.oliver.ren

file=$1
while true
do
    awk '{print $1}' $1|grep -v "^$"|sort|uniq -c > /tmp/tmp.log
    exec < /tmp/tmp.log
    while read line
    do
        ip=`echo $line|awk '{print $2}'`
        count=`echo $line|awk '{print $1}'`
        if [ $count -gt 500 ] && [ `iptables -L -n|grep "$ip"|wc -l` -lt 1 ]
        then
            iptables -I INPUT -s $ip -j DROP
            echo "$line is dropped" >> /tmp/droplist_$(date +%F).log
        fi
    done
    sleep 3600
done
#!/bin/bash
#Author: Oliver King
#Blog: http://www.oliver.ren

file=$1

if expr "$file" : ".*\.log" &> /dev/null
then
    :
else
    echo "usage:$0 xxx.log"
    exit 1
fi

while true
do
    grep "ESTABLISHED" $1|awk -F "[ :]+" '{ ++S[$(NF-3)]}END {for(key in S)print S[key],key}'|sort -rn -k1|head -5 > /tmp/tmp.log
    while read line
    do
        ip=`echo $line|awk '{print $1}'`
        count=`echo $line|awk '{print $1}'`
        if [ $count -gt 500 ] && [ `iptables -L -n|grep "$ip"|wc -l` -lt 1 ]
        then
            iptables -I INPUT -s $ip -j DROP
            echo "$line is dropped" >> /tmp/droplist_$(date +%F).log
        fi
    done</tmp/tmp.log
    sleep 180
done
#!/bin/bash
#Author: Oliver King
#Blog: http://www.oliver.ren

file=$1

function JudgeExt(){
    if expr "$1" : ".*\.log" &> /dev/null
    then
        :
    else
        echo "usage:$0 xxx.log"
        exit 1
    fi
}

function IpCount(){
    grep "ESTABLISHED" $1|awk -F "[ :]+" '{ ++S[$(NF-3)]}END {for(key in S)print S[key], key}'|sort -rn -k1|head -5 > /tmp/tmp.log
}

function ipt(){
    local ip=$1
    if [ `iptables -L -n|grep "$ip"|wc -l` -lt 1 ]
    then
        iptables -I INPUT -s $ip -j DROP
        echo "$line is dropped" >> /tmp/droplist_$(date +%F).log
    fi
}

function main(){
    JudgeExt $file
    while true
    do
        ip=`echo $line|awk '{print $2}'`
        count=`echo $line|awk '{print $1}'`
        if [ $count -gt 3 ]
        then
            ipt $ip
        fi
    done</tmp/tmp.log
    sleep 180
}

main

标签: none