Sobes.tech
Intern

1. Escribir el objeto Python "switches" en formato YAML 2. Transformar "switches" para que solo queden los conmutadores "cisco" 3. Usando el módulo estándar ipaddress, obtener la última dirección del host en la red "172.16.0.0/28" 4. Analizar "dhcp_snooping_table" en una lista de diccionarios de la siguiente forma: dhcp_snooping_table_parsed = [ { "mac": "00:E9:BC:3F:A6:50", "ip": "100.1.1.6", "interface": "FastEthernet0/20", }, { "mac": "00:E9:22:11:A6:50", "ip": "100.1.1.7", "interface": "FastEthernet0/21", } ] 5. Escribir una clase "NetworkSubnet" que tenga 2 métodos: - get_subnet - devuelve la primera subred disponible de la longitud especificada como un objeto de la clase IPv4Network - show_network_pool - devuelve una lista de las subredes disponibles ```python from ipaddress import IPv4Network class NetworkSubnet: def __init__(self, aggregate_network: str): ... def get_subnet(self, length: int) -> IPv4Network: ... def show_network_pool(self) -> list[IPv4Network]: ... net = NetworkSubnet(aggregate_network="172.16.0.0/24") net_1 = net.get_subnet(length=26) print(f"{net_1=}") net_1=IPv4Network('172.16.0.0/26') print(net.get_subnet(length=25)) 172.16.0.128/25 print(net.get_subnet(length=30)) 172.16.0.64/30 print(net.show_network_pool()) [IPv4Network('172.16.0.64/30'), IPv4Network('172.16.0.72/29'), IPv4Network('172.16.0.80/28'), IPv4Network('172.16.0.96/27')] ```

sobes.tech AI

Respuesta de la IA

python import yaml from ipaddress import ip_network, IPv4Network

1. Записать Python объект "switches" в YAML

switches = [ {"vendor": "cisco", "model": "2960"}, {"vendor": "juniper", "model": "ex2200"}, {"vendor": "cisco", "model": "3750"}, ]

with open("switches.yaml", "w") as f: yaml.dump(switches, f)

2. Оставить только cisco коммутаторы

cisco_switches = [sw for sw in switches if sw["vendor"] == "cisco"]

3. Получить последний адрес хоста в сети 172.16.0.0/28

network = ip_network("172.16.0.0/28") last_host = list(network.hosts())[-1]

4. Парсинг dhcp_snooping_table

dhcp_snooping_table = """ 00:E9:BC:3F:A6:50 100.1.1.6 FastEthernet0/20 00:E9:22:11:A6:50 100.1.1.7 FastEthernet0/21 """

dhcp_snooping_table_parsed = [] for line in dhcp_snooping_table.strip().splitlines(): mac, ip, interface = line.split() dhcp_snooping_table_parsed.append({"mac": mac, "ip": ip, "interface": interface})

5. Класс NetworkSubnet

class NetworkSubnet: def init(self, aggregate_network: str): self.aggregate = ip_network(aggregate_network) self.available_subnets = [self.aggregate]

def get_subnet(self, length: int) -> IPv4Network:
    for i, subnet in enumerate(self.available_subnets):
        if subnet.prefixlen <= length:
            # Разбиваем подсеть на более мелкие
            subnets = list(subnet.subnets(new_prefix=length))
            # Берём первую подсеть
            chosen = subnets[0]
            # Обновляем пул доступных подсетей
            self.available_subnets.pop(i)
            self.available_subnets.extend(subnets[1:])
            self.available_subnets.sort(key=lambda x: int(x.network_address))
            return chosen
    raise ValueError("Нет доступных подсетей нужной длины")

def show_network_pool(self) -> list[IPv4Network]:
    return self.available_subnets

Пример использования

net = NetworkSubnet(aggregate_network="172.16.0.0/24") net_1 = net.get_subnet(length=26) print(f"{net_1=}") # 172.16.0.0/26 print(net.get_subnet(length=25)) # 172.16.0.64/25 print(net.get_subnet(length=30)) # 172.16.0.192/30 print(net.show_network_pool()) # Оставшиеся подсети