Python 防止 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()
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。