Intern
16
1. Написать Python объект "switches" в YAML формат 2. Преобразовать "switches" так, что в нём остались "cisco" коммутаторы 3. С помощью стандартного модуля ipaddress получить последний адрес хоста в сети "172.16.0.0/28" 4. Распарсить "dhcp_snooping_table" в список словарей вида: ```python 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. Написать класс "NetworkSubnet" который имеет 2 метода: - get_subnet - возвращает первую доступную подсеть указанной длины в виде объекта класса IPv4Network - show_network_pool - возвращает список доступных подсетей ```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
- Пример объекта
switchesв YAML формате:
switches:
- name: switch1
vendor: cisco
ip: 192.168.1.1
- name: switch2
vendor: juniper
ip: 192.168.1.2
- name: switch3
vendor: cisco
ip: 192.168.1.3
- Преобразование, чтобы оставить только коммутаторы Cisco:
import yaml
with open('switches.yaml') as f:
data = yaml.safe_load(f)
cisco_switches = [sw for sw in data['switches'] if sw['vendor'].lower() == 'cisco']
print(cisco_switches)
- Получение последнего адреса хоста в сети "172.16.0.0/28":
import ipaddress
network = ipaddress.ip_network('172.16.0.0/28')
last_host = network.broadcast_address - 1
print(last_host) # 172.16.0.14
- Парсинг
dhcp_snooping_tableв список словарей:
dhcp_snooping_table = '''
MacAddress IpAddress Interface
00:E9:BC:3F:A6:50 100.1.1.6 FastEthernet0/20
00:E9:22:11:A6:50 100.1.1.7 FastEthernet0/21
'''
lines = dhcp_snooping_table.strip().split('\n')[1:] # пропускаем заголовок
parsed = []
for line in lines:
mac, ip, interface = line.split()
parsed.append({"mac": mac, "ip": ip, "interface": interface})
print(parsed)
- Класс
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:
# Разбиваем подсеть на более мелкие
subnets = list(subnet.subnets(new_prefix=length))
if subnets:
allocated = subnets[0]
# Обновляем пул доступных подсетей
remaining = subnets[1:] + self.available_subnets[:i] + self.available_subnets[i+1:]
self.available_subnets = remaining
return allocated
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())