利用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 <<EOF
from: monitor@zhaoyun.com
to:15101507336@139.com
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 <<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脚本 
邮件收到的效果

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


本文转自zhaoyun00 51CTO博客,原文链接:http://blog.51cto.com/zhaoyun/606878
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值