Original Source: Learn python step by step
This weekend, it was a headache. The website suddenly couldn't be opened, and it was a tragedy to quickly connect remotely. ssh couldn't be connected, and it always timed out. The first response was ddos attacks.
The data center was contacted and said that the traffic was full. What's even more tragic is that there was no hardware firewall in the data center, and there was no way to go to the data center and find the IP address.
The result cannot be found. For full screen connections, only a few IP addresses with a large number of accesses can be checked in the case of network disconnection.
However, this solution can only be used for a short period of time, but it won't take long before it can be solved. data centers without hardware firewalls cannot afford to be hurt. However, on weekends, data centers cannot be shelved and cannot be replaced, you have to do that first.
Ddos attacks on the Internet are very detailed, but it is really troublesome to prevent them without a hardware firewall, I want to write a script to check the number of requests from a specified IP address within a fixed period of time, and use iptables to disable the source of the suspected attack from seeing the anti-DDoS script 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.exe cute ("create table ddos (ip text unique, date integer );")
Except t:
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.exe cute ('replace into ddos values (?,?) ', (Ip, int (time. time ())))
Time. sleep (0.1)
Db. commit ()
# Unblocking outdated blockings
C.exe cute ("select * from ddos ")
Ddos = c. fetchall ()
For ip, date in ddos:
If date + OUTDATE_TIME <time. time ():
C.exe cute ("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 ()