Python防止DDos攻击

原始出处: 一步一步学python

这个周末叫一个烦啊,网站突然打不开了,赶紧的远程连上去看看是啥问题 结果悲剧了,ssh连不上去,总是超时 第一反应就是被ddos了

联系机房结果说流量占满了,更悲剧的是这个机房竟然没有硬件防火墙,没有办法只能跑去机房看看找下IP了 结果一查不得了啊,满屏的连接,唯有先断网查查几个访问比较多的IP

不过这治标不治本的方法只能维持很短时间,没过多久就又不行了,没有硬件防火墙的机房伤不起啊 不过周末机房都不给安排上架,也就不能换机房了,只好先就那样挂着吧

网上有关ddos的攻击说的很详细了,不过在没有硬件防火墙的情况下要防住还真是件麻烦事,就想写个脚本 检测固定时间内的指定IP的请求数,把疑似攻击的源用iptables禁止掉 无意见看到防DDos攻击in python

from subprocess import Popen,PIPE import re import time import sqlite3  CONCURRENCY_ALLOWED = 30 OUTDATE_TIME = 86400  # initializing database db = sqlite3.connect("/tmp/ddos.db3") c = db.cursor() try:     c.execute("create table ddos (ip text unique,date integer);") except:     print "database exists"  # blocking ips has more than CONCURRENCY_ALLOWED connections pipe = Popen("netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n >                                       /tmp/ddos.txt",shell=True,bufsize=1024,stdout=PIPE).stdout #ddos = pipe.read() ddos = open("/tmp/ddos.txt").read() ct = re.compile(r"(\S+)\s+(\S+).* ").findall(ddos) for count,ip in ct:     if int(count)>CONCURRENCY_ALLOWED and (ip != "127.0.0.1") and (not ip.startswith("192.168")):         out = Popen("iptables -I INPUT -s %s -j DROP"%ip,shell=True,bufsize=1024,stdout=PIPE).stdout         print "blocking %s for %s visits" % (ip,count)         c.execute('replace into ddos values (?,?)',(ip,int(time.time())))         time.sleep(0.1) db.commit()  # unblocking outdated blockings c.execute("select * from ddos") ddos = c.fetchall() for ip,date in ddos:     if date + OUTDATE_TIME < time.time():         c.execute("delete from ddos where ip=?",(ip,))         print "unblocking %s" % ip         out = Popen("iptables -D INPUT -s %s -j DROP"%ip,shell=True,                      bufsize=1024,stdout=PIPE).stdout         time.sleep(0.1) db.commit()

也不用自己写了,明天准备换机房不过也把这个放进去做第二手准备,还是建议大家找一个规模大点的IDC机房,硬件措施跟不上的你伤不起啊

转载于:https://my.oschina.net/tenking/blog/31906

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值