1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
| import argparse import csv import re from collections import Counter, defaultdict from urllib.parse import unquote
RULES = { "SQL注入": [ r"union\s+select", r"\bor\s+1=1\b", r"\band\s+1=1\b", r"sleep\s*\(", r"benchmark\s*\(", r"information_schema", r"(--|%2d%2d|#|%23)" ], "XSS探测": [ r"<script", r"%3cscript", r"onerror", r"onload", r"javascript:", r"alert\s*\(" ], "敏感路径访问": [ r"/\.git/config", r"/\.env", r"/admin", r"/phpinfo\.php", r"/backup", r"/config\.php" ], "命令执行探测": [ r"cmd=", r"whoami", r"\bid\b", r"uname", r"/bin/bash", r"curl\s+", r"wget\s+" ], "疑似登录爆破": [ r"post\s+/login", r"post\s+/admin", r"post\s+/user/login" ] }
LOG_PATTERN = re.compile( r'(?P<ip>\S+) \S+ \S+ \[(?P<time>.*?)\] ' r'"(?P<method>\S+)\s+(?P<url>\S+)\s+(?P<protocol>[^"]+)" ' r'(?P<status>\d+) (?P<size>\S+) ' r'"(?P<referer>[^"]*)" "(?P<ua>[^"]*)"' )
def parse_line(line): match = LOG_PATTERN.search(line) if not match: return None
data = match.groupdict() data["decoded_url"] = unquote(data["url"]) return data
def detect(record): text = f'{record["method"]} {record["decoded_url"]} {record["ua"]}'.lower() hits = []
for attack_type, rules in RULES.items(): for rule in rules: if re.search(rule, text, re.IGNORECASE): hits.append(attack_type) break
return hits
def analyze(log_path): attack_counter = Counter() ip_counter = Counter() url_counter = Counter() status_counter = Counter() timeline = defaultdict(list) rows = []
with open(log_path, "r", encoding="utf-8", errors="ignore") as f: for line in f: record = parse_line(line) if not record: continue
hits = detect(record) if not hits: continue
ip = record["ip"] url = record["decoded_url"] status = record["status"]
ip_counter[ip] += 1 url_counter[url] += 1 status_counter[status] += 1
for hit in hits: attack_counter[hit] += 1 timeline[ip].append((record["time"], hit, record["method"], url, status)) rows.append({ "ip": ip, "time": record["time"], "attack_type": hit, "method": record["method"], "url": url, "status": status, "user_agent": record["ua"] })
return attack_counter, ip_counter, url_counter, status_counter, timeline, rows
def write_csv(rows, output): if not rows: return
fields = ["ip", "time", "attack_type", "method", "url", "status", "user_agent"] with open(output, "w", newline="", encoding="utf-8-sig") as f: writer = csv.DictWriter(f, fieldnames=fields) writer.writeheader() writer.writerows(rows)
def print_top(title, counter, limit=10): print(f"\n[+] {title}") for key, value in counter.most_common(limit): print(f"{value:>5} {key}")
def main(): parser = argparse.ArgumentParser(description="Web access log attack feature extractor") parser.add_argument("-f", "--file", required=True, help="access.log path") parser.add_argument("-o", "--output", default="result.csv", help="CSV output path") args = parser.parse_args()
attack_counter, ip_counter, url_counter, status_counter, timeline, rows = analyze(args.file)
print_top("攻击类型统计", attack_counter) print_top("异常 IP TOP 10", ip_counter) print_top("异常 URL TOP 10", url_counter) print_top("状态码统计", status_counter)
print("\n[+] 攻击时间线示例") for ip, events in list(timeline.items())[:5]: print(f"\nIP: {ip}") for time, attack_type, method, url, status in events[:10]: print(f"{time} [{attack_type}] {method} {url} status={status}")
write_csv(rows, args.output) print(f"\n[+] CSV 已导出: {args.output}")
if __name__ == "__main__": main()
|