Sobes.tech
Intern

1. Écrire l'objet Python "switches" au format YAML 2. Transformer "switches" pour ne conserver que les commutateurs "cisco" 3. Utiliser le module standard ipaddress pour obtenir la dernière adresse d'hôte dans le réseau "172.16.0.0/28" 4. Analyser "dhcp_snooping_table" en une liste de dictionnaires au format suivant: dhcp_snooping_table_parsed = [ { "mac": "00:E9:8C: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. Écrire une classe "NetworkSubnet" avec 2 méthodes: get_subnet - retourne la première sous-réseau disponible de la longueur spécifiée en tant qu'objet de la classe IPv4Network show_network_pool - retourne une liste de sous-réseaux disponibles 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.0/30'), IPv4Network('172.16.0.72/29'), IPv4Network('172.16.0.80/28'), IPv4Network('172.16.0.96/27')]

sobes.tech IA

Réponse de l'IA

python import yaml from ipaddress import ip_network, IPv4Network

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

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

yaml_data = yaml.dump(switches, allow_unicode=True) print(yaml_data)

2. Преобразовать "switches" так, чтобы остались только "cisco" коммутаторы

cisco_switches = [sw for sw in switches if sw.get('vendor') == 'cisco'] print(cisco_switches)

3. С помощью ipaddress получить последний адрес хоста в сети "172.16.0.0/28"

network = ip_network('172.16.0.0/28') last_host = list(network.hosts())[-1] print(last_host) # 172.16.0.14

4. Распарсить dhcp_snooping_table в список словарей

dhcp_snooping_table = [ "00:E9:8C: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: mac, ip, interface = line.split() dhcp_snooping_table_parsed.append({"mac": mac, "ip": ip, "interface": interface})

print(dhcp_snooping_table_parsed)

5. Класс NetworkSubnet

from ipaddress import IPv4Network

class NetworkSubnet: def init(self, aggregate_network: str): self.aggregate = IPv4Network(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 and subnet.prefixlen <= length <= subnet.max_prefixlen:
            # Разбиваем подсеть на более мелкие
            subnets = list(subnet.subnets(new_prefix=length))
            if subnets:
                allocated = subnets[0]
                # Обновляем пул доступных подсетей
                # Удаляем выделенную подсеть
                del self.available_subnets[i]
                # Добавляем оставшиеся подсети
                self.available_subnets.extend(subnets[1:])
                return allocated
    raise ValueError(f"No available subnet with prefix length {length}")

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=}") # IPv4Network('172.16.0.0/26') print(net.get_subnet(length=25)) # 172.16.0.64/25 или 172.16.0.128/25 в зависимости от реализации print(net.get_subnet(length=30)) # 172.16.0.128/30 или другая доступная подсеть print(net.show_network_pool()) # Список оставшихся подсетей


Обратите внимание, что в реализации класса NetworkSubnet метод get_subnet выделяет первую доступную подсеть нужной длины, обновляя пул доступных подсетей.