0°

利用python脚本自动拦截DDOS攻击

改成python试试

一个很实用的iptables脚本,实现自动拒绝可疑IP地址,并发送报警邮件,短信
linux:~ # cat  iptables

#!/bin/bash
touch /root/back_bad_ip.txt
time=

1
1`

date +"%Y-%m-%d %H:%M:%S"

1
1`

ar=

1
1`

wc -l /root/back_bad_ip.txt |awk '{print $1}'

1
1`

sleep 1
#红色自己改有端口, SYN_RECV等
netstat -an |
grep 80 |grep -v "STREAM"|awk '{print $5 }'|sort | awk -F: '{print $1}'|uniq -c |awk '$1 > 100 {print $1,$2}' > /root/bad_ip ;
cat bad_ip |awk -vtime="$time" '{print time"    |    " $1"    |    "$2}' >>/root/back_bad_ip.txt
ar2=

1
1`

wc -l /root/back_bad_ip.txt |awk '{print $1}'

1
1`

for i in

1
1`

awk '{print $2}' /root/bad_ip

1
1`

do
iptables -I INPUT -s $i -j DROP
done
i1=

1
1`

echo "$ar2-$ar" |bc

1
1`

tail0=

1
1`

tail -n $i1 /root/back_bad_ip.txt

1
1`

for i2 in

1
1`

echo "$ar2-$ar" |bc

1
1`

do
if ([ $i2 -gt 0  ]&&[ $i2 -lt 5 ]) ; then
sendmail -t <<EOF
from: monitor@zhaoyun.com
to:15101507336@139.com
subject: warning
$time 你的系统可能被攻击,请尽快作出响应,目前有$i1个攻击源IP地址,系统已经帮你拦截。
$tail0
EOF
fi
done
tail5=

1
1`

tail -n $i1 /root/back_bad_ip.txt

1
1`

for i2 in

1
1`

echo "$ar2-$ar" |bc

1
1`

do
if [ $i2 -gt 5 ] ; then
sendmail -t <<EOF
from: monitor@zhaoyun.com
to:15101507336@139.com
subject: Serious warning
$time 你的系统正在被攻击,请尽快作出响应,目前有$i1个攻击源IP地址,系统已经帮你拦截。
$tail5
EOF
fi
done

自己写的,shell不会用,但是这个脚本肯定好用。
可以在back_bad_ip.txt中查看到连接的记录 ,做到有据可查
linux:~ # cat back_bad_ip.txt
时间                建立连接的次数       IP地址

2011-07-09 08:59:37  |   127    |   118.144.78.36
2011-07-09 08:59:37  |   211    |   118.144.78.37
2011-07-09 08:59:37  |   115    |   118.144.78.38
2011-07-09 08:59:37  |   113    |   118.144.78.42
把这个脚本放在后台执行  
linux:~ # /root/10_seconds &

linux:~ # cat 10_seconds

#!/bin/bash
while [ 1 ]
do
/root/iptables
sleep 10
done

他会每10秒钟执行一次/root/iptables脚本
邮件收到的效果
084337868.jpg 只有在有人攻击的情况下才生效 这个有个缺点就是,10秒钟执行一次的话如果有攻击会有很多重复的 规则添加到IPTABLES规则中,建议固定的规则保存在配置文件中。在一定的时间重启一次iptables服务,来清空自动添加的规则。  不影响原有规则 。

「点点赞赏,手留余香」

    还没有人赞赏,快来当第一个赞赏的人吧!