分布式拒绝服务(DDoS)攻击通过大量恶意流量淹没服务器资源,导致服务瘫痪。本文将提供一套结合代码实现的主动防御方案,涵盖流量监控、自动化拦截和基础设施优化。
1. 实时流量监控与告警
目标 :检测异常流量并触发告警
工具 :Python
+ tshark
(Wireshark命令行工具)
代码示例:
python
import subprocess
import time
def monitor_traffic(interface='eth0', threshold=1000):
while True:
# 统计每秒接收的SYN包数量(SYN Flood常见特征)
cmd = f"tshark -i {interface} -a duration:1 -Y 'tcp.flags.syn==1' -q -z stats"
result = subprocess.getoutput(cmd)
packet_count = int(result.split()[-2]) # 提取SYN包数量
if packet_count > threshold:
print(f"[!] 异常流量告警: 检测到 {packet_count} 个SYN包/秒")
# 触发防火墙规则(见下文)
block_ip_script()
time.sleep(1)
if __name__ == "__main__":
monitor_traffic(threshold=500) # 根据业务调整阈值
2. 自动封禁恶意IP
工具 :iptables
+ Python
代码示例(自动封禁高频访问IP):
bash
# 手动操作命令:
iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m recent --set
iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m recent --update --seconds 60 --hitcount 100 -j DROP
python
# 自动化脚本扩展:基于日志分析封禁IP
import os
from collections import defaultdict
def analyze_log(log_path='/var/log/nginx/access.log'):
ip_count = defaultdict(int)
with open(log_path) as f:
for line in f:
ip = line.split()[0]
ip_count[ip] += 1
for ip, count in ip_count.items():
if count > 300: # 1分钟内超过300次请求
os.system(f"iptables -A INPUT -s {ip} -j DROP")
print(f"已封禁IP: {ip}")
analyze_log()
3. 基础设施优化
方案1:启用CDN隐藏真实IP
nginx
# Nginx配置示例:限制单个IP连接数
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location / {
limit_conn addr 20; # 每个IP最大20连接
proxy_pass http://backend_server;
}
}
}
方案2:云服务商API自动扩容
python
# AWS自动扩容示例(使用boto3)
import boto3
def auto_scaling():
cloudwatch = boto3.client('cloudwatch')
# 监控CPU使用率
metrics = cloudwatch.get_metric_statistics(
Namespace='AWS/EC2',
MetricName='CPUUtilization',
Dimensions=[{'Name':'InstanceId', 'Value':'i-1234567890abcdef0'}],
StartTime=datetime.utcnow() - timedelta(minutes=5),
EndTime=datetime.utcnow(),
Period=300,
Statistics=['Average']
)
if metrics['Datapoints'][0]['Average'] > 90:
autoscale = boto3.client('autoscaling')
autoscale.set_desired_capacity(
AutoScalingGroupName='my-asg',
DesiredCapacity=10 # 扩容到10个实例
)
总结
- 通过实时监控识别攻击特征
- 使用iptables和自动化脚本快速响应
- 结合CDN和云服务弹性扩容分散流量压力
- 定期测试防御方案有效性(推荐使用
slowloris
等工具模拟攻击)