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

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

linux:~ # cat iptables

#!/bin/bash

touch /root/back_bad_ip.txt

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

ar=`wc -l /root/back_bad_ip.txt |awk '{print $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=`wc -l /root/back_bad_ip.txt |awk '{print $1}'`

for i in `awk '{print $2}' /root/bad_ip`

do

iptables -I INPUT -s $i -j DROP

done

i1=`echo "$ar2-$ar" |bc `

tail0=`tail -n $i1 /root/back_bad_ip.txt`

for i2 in `echo "$ar2-$ar" |bc`

do

if ([ $i2 -gt 0 ]&&[ $i2 -lt 5 ]) ; then

sendmail -t <

from: monitor@https://www.360docs.net/doc/ee17695294.html,

to:151********@https://www.360docs.net/doc/ee17695294.html,

subject: warning

$time 你的系统可能被攻击,请尽快作出响应,目前有$i1个攻击源IP地址,系统已经帮你拦截。

$tail0

EOF

fi

done

tail5=`tail -n $i1 /root/back_bad_ip.txt`

for i2 in `echo "$ar2-$ar" |bc`

do

if [ $i2 -gt 5 ] ; then

sendmail -t <

from: monitor@https://www.360docs.net/doc/ee17695294.html,

to:151********@https://www.360docs.net/doc/ee17695294.html,

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脚本

邮件收到的效果

只有在有人攻击的情况下才生效

这个有个缺点就是,10秒钟执行一次的话如果有攻击会有很多重复的规则添加到IPTABLES规则中,建议固定的规则保存在配置文件中。在一定的时间重启一次iptables服务,来清空自动添加的规则。不影响原有规则。

相关主题
相关文档
最新文档