SoFunction
Updated on 2024-11-14

Anti-DDoS scripts implemented in python


from subprocess import Popen,PIPE
import re
import time
import sqlite3
CONCURRENCY_ALLOWED = 30
OUTDATE_TIME = 86400
# initializing database
db = ("/tmp/ddos.db3")
c = ()
try:
("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/",shell=True,bufsize=1024,stdout=PIPE).stdout
#ddos = ()
ddos = open("/tmp/").read()
ct = (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 ("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)
('replace into ddos values (?,?)',(ip,int(())))
(0.1)
()
# unblocking outdated blockings
("select * from ddos")
ddos = ()
for ip,date in ddos:
if date + OUTDATE_TIME < ():
("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
(0.1)
()