管理员
|
阅读:2092回复:0
Python防止ddos 攻击
楼主#
更多
发布于:2011-10-23 21:13
 | |  |  | 这个周末叫一个烦啊,网站突然打不开了,赶紧的远程连上去看看是啥问题 结果悲剧了,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+).*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()
| |  | |  |
|