• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python实现的防DDoS脚本

python 搞代码 4年前 (2022-01-09) 18次浏览 已收录 0个评论

这篇博可以说连开场白都可以省掉了,之所以被DDoS,并不是因为惹了疯狗被追着咬,而是因为VC悲剧之后流量全到simplecd来了。
不仅如此,一些笨蛋们在抓站,一些笨蛋们在用迅雷下载,100Mbps的端口居然已经满负荷运作十几个小时了,这是什么概念?100Mbps满负荷1天,流量就是1000G,这样下去不用多久,我就可以等着上百刀的罚单了,泪飙。
此外,100Mbps的速度使得硬盘都快转不动了,严重拖累网站的响应速度,卡得我欲仙欲死啊真是。想当年VC挂了一天,被抓站的家伙们搞得一个礼拜半残废状态(其中那些家伙包括我在内,汗)。simplecd就更支撑不了了。
事实上这种人肉DDoS比正常的DDoS更加难以区分和预防,不过也就只能尽人事,听天命了,参考一些文章写了个python的防止DDoS的脚本,加入cron每分钟执行即可。
实现原理是,查询netstat的连接数,同IP超过一定连接的用iptables封禁一定时间,自动封禁,自动解封。

 <BR>from subprocess import Popen,PIPE <BR>import re <BR>import time <BR>import sqlite3 <BR>CONCURRENCY_ALLOWED = 30 <BR>OUTDATE_TIME = 86400 <BR># initializing database <BR>db = sqlite3.connect("/tmp/ddos.db3") <BR>c = db.cursor() <BR>try: <BR>c.execute("create table ddos (ip text unique,date integer);") <BR>except: <BR>print "database exists" <BR># blocking ips has more than CONCURRENCY_ALLOWED connections <BR>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 <BR>#ddos = pipe.read()<strong>本文来源gao@daima#com搞(%代@#码@网2</strong> <BR>ddos = open("/tmp/ddos.txt").read() <BR>ct = re.compile(r"(\S+)\s+(\S+).*\n").findall(ddos) <BR>for count,ip in ct: <BR>if int(count)>CONCURRENCY_ALLOWED and (ip != "127.0.0.1") and (not ip.startswith("192.168")): <BR>out = Popen("iptables -I INPUT -s %s -j DROP"%ip,shell=True,bufsize=1024,stdout=PIPE).stdout <BR>print "blocking %s for %s visits" % (ip,count) <BR>c.execute('replace into ddos values (?,?)',(ip,int(time.time()))) <BR>time.sleep(0.1) <BR>db.commit() <BR># unblocking outdated blockings <BR>c.execute("select * from ddos") <BR>ddos = c.fetchall() <BR>for ip,date in ddos: <BR>if date + OUTDATE_TIME < time.time(): <BR>c.execute("delete from ddos where ip=?",(ip,)) <BR>print "unblocking %s" % ip <BR>out = Popen("iptables -D INPUT -s %s -j DROP"%ip,shell=True,bufsize=1024,stdout=PIPE).stdout <BR>time.sleep(0.1) <BR>db.commit() <BR>


目前来说这个脚本的效果是0,封了500多号人了,但是还是满速,真是可怕。
24日 更新:
同时用这个脚本,外加转移桌面版的站点到一个10M unlimited的地方以后,似乎天下太平了(吗?)


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python实现的防DDoS脚本
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址