防DDoS脚本 in python

observer专栏杂记 2011-01-23 22:31:26 累计浏览 7,000 次

    这篇博可以说连开场白都可以省掉了,之所以被DDoS,并不是因为惹了疯狗被追着咬,而是因为VC悲剧之后流量全到simplecd来了。

    不仅如此,一些笨蛋们在抓站,一些笨蛋们在用迅雷下载,100Mbps的端口居然已经满负荷运作十几个小时了,这是什么概念?100Mbps满负荷1天,流量就是1000G,这样下去不用多久,我就可以等着上百刀的罚单了,泪飙。

    此外,100Mbps的速度使得硬盘都快转不动了,严重拖累网站的响应速度,卡得我欲仙欲死啊真是。想当年VC挂了一天,被抓站的家伙们搞得一个礼拜半残废状态(其中那些家伙包括我在内,汗)。simplecd就更支撑不了了。

    事实上这种人肉DDoS比正常的DDoS更加难以区分和预防,不过也就只能尽人事,听天命了,参考一些文章写了个python的防止DDoS的脚本,加入cron每分钟执行即可。

    实现原理是,查询netstat的连接数,同IP超过一定连接的用iptables封禁一定时间,自动封禁,自动解封。

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+).*\n").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()
    目前来说这个脚本的效果是0,封了500多号人了,但是还是满速,真是可怕。

24日 更新:
同时用这个脚本,外加转移桌面版的站点到一个10M unlimited的地方以后,似乎天下太平了(吗?)
原图已失效

同分类推荐文章

  1. 全盘加密应对的威胁模型、分层设计与实践 (2026-11-14 03:10:02)
  2. 别了,SMTP mTLS (2026-11-14 00:10:02)
  3. Stop Writing Authentication Checks Into Every Service. Combine Them in your Kubernetes Gateway. (2026-10-27 13:40:42)

查看更多 安全 文章 →

建议继续学习

  1. 用Hyer来进行网站的抓取 (累计阅读 158,836)
  2. 配置Nginx+uwsgi更方便地部署python应用 (累计阅读 109,256)
  3. 程序员技术练级攻略 (累计阅读 36,061)
  4. python实现自动登录discuz论坛 (累计阅读 33,280)
  5. python编程细节──遍历dict的两种方法比较 (累计阅读 21,007)
  6. 每个程序员都应该学习使用Python或Ruby (累计阅读 18,309)
  7. Chrome和goagent的配置方法,你懂的 (累计阅读 17,490)
  8. 30分钟3300%性能提升――python+memcached网页优化小记 (累计阅读 14,112)
  9. 使用python爬虫抓站的一些技巧总结:进阶篇 (累计阅读 13,775)
  10. 我的PHP,Python和Ruby之路 (累计阅读 13,718)