بتل کد Battle Codeدارد باز می‌شود…

جواب «Step 3: The Report» چالش 6 از جلسه‌ی 22

سؤال

(سخت‌تر) قدم ۳: بعد از خروجی قدم ۲ گزارش را چاپ کن: یک خط report: 9 packets, 3 allowed, 6 denied, 1 alerts، بعد برای هر IP در alerts یک خط block next: 198.51.100.4، و آخر از همه phase 1 complete: well done, network detective!. عددها را از متغیرها بگیر، نه دستی.

راهنما

print(f"report: {len(packets)} packets, {allowed} allowed, {denied} denied, {len(alerts)} alerts")، بعد for ip in alerts:.

یک جواب درست

import ipaddress
rules = [
    {"action": "deny", "src": "203.0.113.9/32", "port": "any"},
    {"action": "allow", "src": "10.20.0.0/16", "port": 443},
    {"action": "allow", "src": "10.20.0.0/16", "port": 53},
    {"action": "allow", "src": "0.0.0.0/0", "port": 80},
]
packets = [
    {"src": "10.20.1.5", "port": 443},
    {"src": "203.0.113.9", "port": 443},
    {"src": "198.51.100.4", "port": 22},
    {"src": "198.51.100.4", "port": 23},
    {"src": "10.20.1.8", "port": 53},
    {"src": "198.51.100.4", "port": 3389},
    {"src": "192.0.2.77", "port": 80},
    {"src": "198.51.100.4", "port": 445},
    {"src": "10.20.1.5", "port": 22},
]

def decide(src, port):
    for r in rules:
        net = ipaddress.ip_network(r["src"])
        if ipaddress.ip_address(src) in net and (r["port"] == "any" or r["port"] == port):
            return r["action"]
    return "deny"

allowed = 0
denied = 0
for p in packets:
    action = decide(p["src"], p["port"])
    print(action, p["src"], "->", p["port"])
    if action == "allow":
        allowed = allowed + 1
    else:
        denied = denied + 1
ports = {}
for p in packets:
    if p["src"] not in ports:
        ports[p["src"]] = set()
    ports[p["src"]].add(p["port"])
alerts = []
for ip in ports:
    if len(ports[ip]) >= 4:
        print(f"alert scan {ip} ({len(ports[ip])} ports)")
        alerts.append(ip)
print(f"report: {len(packets)} packets, {allowed} allowed, {denied} denied, {len(alerts)} alerts")
for ip in alerts:
    print("block next:", ip)
print("phase 1 complete: well done, network detective!")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن