defdetect_pattern(ip): patterns = defaultdict(int) for req_ip, url in request_log: if req_ip == ip: query = re.findall(r'query=(.*)', url) if query: patterns[query[0]] += 1 # 假设如果一个查询出现超过3次,就标记为可疑 for count in patterns.values(): if count > 3: returnTrue returnFalse
from flask import Flask, request, jsonify import time
app = Flask(__name__)
# 存储被封禁的IP和封禁时间 banned_ips = {}
@app.before_request defcheck_ip(): client_ip = request.remote_addr # 检查IP是否被封禁 if client_ip in banned_ips: ban_time, duration = banned_ips[client_ip] if time.time() < ban_time + duration: return jsonify({"error": " Your IP is temporarily banned."}), 403 else: del banned_ips[client_ip] # 解除封禁
# 假设检查频率,只是在演示 if is_suspicious_activity(client_ip): banned_ips[client_ip] = (time.time(), 300) # 封禁5分钟 return jsonify({"error": "Too many requests, you are temporarily banned."}), 403
# 连接数据库 conn = sqlite3.connect('banned_ips.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS banned_ips (ip TEXT PRIMARY KEY, banned_time REAL)''') conn.commit()
defcheck_permanent_ban(ip): c.execute("SELECT * FROM banned_ips WHERE ip=?", (ip,)) return c.fetchone() isnotNone
defban_permanently(ip): c.execute("INSERT OR REPLACE INTO banned_ips (ip, banned_time) VALUES (?, ?)", (ip, time.time())) conn.commit()
@app.before_request defcheck_ip(): client_ip = request.remote_addr # 检查永久封禁 if check_permanent_ban(client_ip): return jsonify({"error": "Your IP is permanently banned."}), 403
if client_ip in banned_ips: ban_time, duration = banned_ips[client_ip] if time.time() < ban_time + duration: return jsonify({"error": "Your IP is temporarily banned."}), 403 else: del banned_ips[client_ip]
if is_suspicious_activity(client_ip): # 如果是恶意行为,考虑永久封禁 ban_permanently(client_ip) return jsonify({"error": "Your IP has been permanently banned due to malicious activity."}), 403
defclean_blacklist(): current_time = get_current_time() for ip inlist(blacklist): if ip_last_access_time[ip] < current_time - timedelta(days=30): blacklist.remove(ip)
# 读取日志文件 withopen(log_file_path, 'r') as file: for line in file: # 使用正则表达式提取IP地址 match = re.search(r'(\d+\.\d+\.\d+\.\d+)', line) ifmatch: ip_address = match.group(1) user_access_counts[ip_address] += 1
# 输出每个用户的访问次数 for ip, count in user_access_counts.items(): print(f'IP: {ip}, 访问次数: {count}')
custom_user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1' headers = { 'User-Agent': custom_user_agent }
验证码(Completely Automated Public Turing test to tell Computers and Humans Apart)是一种用于区分人类用户与机器用户的机制。它通常要求用户完成某种形式的认证,以确保提交请求的是一个真实的人。验证码在防止网络爬虫、恶意注册等方面起到了重要作用。