Guest User

Untitled

a guest
Jul 20th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. from subprocess import Popen,PIPE
  2. import re
  3. import time
  4. import sqlite3
  5.  
  6. CONCURRENCY_ALLOWED = 30
  7. OUTDATE_TIME = 86400
  8.  
  9. # initializing database
  10. db = sqlite3.connect("/tmp/ddos.db3")
  11. c = db.cursor()
  12. try:
  13. c.execute("create table ddos (ip text unique,date integer);")
  14. except:
  15. print "database exists"
  16.  
  17. # blocking ips has more than CONCURRENCY_ALLOWED connections
  18. 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
  19. #ddos = pipe.read()
  20. ddos = open("/tmp/ddos.txt").read()
  21. ct = re.compile(r"(\S+)\s+(\S+).*\n").findall(ddos)
  22. for count,ip in ct:
  23. if int(count)>CONCURRENCY_ALLOWED and (ip != "127.0.0.1") and (not ip.startswith("192.168")):
  24. out = Popen("iptables -I INPUT -s %s -j DROP"%ip,shell=True,bufsize=1024,stdout=PIPE).stdout
  25. print "blocking %s for %s visits" % (ip,count)
  26. c.execute('replace into ddos values (?,?)',(ip,int(time.time())))
  27. time.sleep(0.1)
  28. db.commit()
  29.  
  30. # unblocking outdated blockings
  31. c.execute("select * from ddos")
  32. ddos = c.fetchall()
  33. for ip,date in ddos:
  34. if date + OUTDATE_TIME < time.time():
  35. c.execute("delete from ddos where ip=?",(ip,))
  36. print "unblocking %s" % ip
  37. out = Popen("iptables -D INPUT -s %s -j DROP"%ip,shell=True,bufsize=1024,stdout=PIPE).stdout
  38. time.sleep(0.1)
  39. db.commit()
Add Comment
Please, Sign In to add comment