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

جواب «Step 1: Design» چالش 4 از جلسه‌ی 34

سؤال

قدم ۱: برای هر دستگاه (به ترتیب) بخشش را با zone_of پیدا کن و ایرادهایش را به این ترتیب بگو: دستگاهی با kind برابر smart که بخشش smart نیست: move to the smart zone؛ رمزش در DEFAULTS است: change the default password. هر ایراد یک خط مثل door-cam (family): move to the smart zone؛ دستگاه بی‌ایراد my-laptop (family): ok. ایرادها را در problems بشمار (قدم ۳ لازمش دارد). خروجی:
my-laptop (family): ok
mum-phone (family): ok
smart-tv (smart): ok
door-cam (family): move to the smart zone
door-cam (family): change the default password
speaker (smart): change the default password
guest-phone (guest): ok
design problems: 3

راهنما

مثل جلسه‌ی ۲۵ یک فهرست found با دو if جدا: d["kind"] == "smart" and z != "smart" و d["password"] in DEFAULTS. بعد ok یا هر ایراد، و problems = problems + len(found).

یک جواب درست

import ipaddress

zones = {
    "family": "192.168.1.0/24",
    "guest": "192.168.50.0/24",
    "smart": "192.168.60.0/24",
}
DEFAULTS = ["admin", "1234", "password", "0000", "12345"]
devices = [
    {"name": "my-laptop", "ip": "192.168.1.10", "kind": "computer", "password": "Kite-Moon-River-7"},
    {"name": "mum-phone", "ip": "192.168.1.11", "kind": "phone", "password": "Tea-Garden-Lamp-3"},
    {"name": "smart-tv", "ip": "192.168.60.4", "kind": "smart", "password": "Owl-Rain-Cup-58"},
    {"name": "door-cam", "ip": "192.168.1.30", "kind": "smart", "password": "admin"},
    {"name": "speaker", "ip": "192.168.60.7", "kind": "smart", "password": "1234"},
    {"name": "guest-phone", "ip": "192.168.50.20", "kind": "phone", "password": "Sky-Bike-Pear-90"},
]
allowed = [
    ("family", "family"),
    ("family", "smart"),
    ("family", "internet"),
    ("guest", "internet"),
    ("smart", "internet"),
]
decoy_ports = [2323]
traffic = [
    ("192.168.1.10", "203.0.113.20", 443),
    ("192.168.50.20", "192.168.1.10", 445),
    ("192.168.1.11", "192.168.60.4", 8008),
    ("192.168.60.7", "192.168.1.10", 22),
    ("203.0.113.66", "192.168.1.30", 2323),
    ("192.168.60.4", "203.0.113.50", 443),
    ("192.168.1.30", "192.168.1.10", 2323),
]

def zone_of(ip):
    for name in zones:
        if ipaddress.ip_address(ip) in ipaddress.ip_network(zones[name]):
            return name
    return "internet"

problems = 0
for d in devices:
    z = zone_of(d["ip"])
    found = []
    if d["kind"] == "smart" and z != "smart":
        found.append("move to the smart zone")
    if d["password"] in DEFAULTS:
        found.append("change the default password")
    if len(found) == 0:
        print(d["name"], "(" + z + "): ok")
    for f in found:
        print(d["name"], "(" + z + "):", f)
    problems = problems + len(found)
print("design problems:", problems)

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