import subprocess import ipaddress from dialog import Dialog class NetworkConfig: def __init__(self): self.d = Dialog(dialog="dialog") self.temp_network_settings = {} def select_interface(self): interfaces = self.get_network_interfaces() if not interfaces: self.d.msgbox("Нет доступных сетевых интерфейсов.") return None code, tag = self.d.menu( "Выберите интерфейс:", choices=[(iface, "") for iface in interfaces] ) if code == self.d.OK: self.d.msgbox(f"Выбран интерфейс: {tag}") self.show_current_settings(tag) # Добавлено окно с текущими настройками return tag else: self.d.msgbox("Интерфейс не выбран.") return None @staticmethod def get_network_interfaces(): try: result = subprocess.run( ["ls", "/sys/class/net/"], capture_output=True, text=True, check=True ) interfaces = result.stdout.strip().split("\n") return interfaces except subprocess.CalledProcessError: return [] def show_current_settings(self, interface): try: result = subprocess.run( ["ip", "-o", "addr", "show", interface], capture_output=True, text=True, check=True ) current_settings = result.stdout.strip() ip_address = None if "inet " in current_settings: ip_address = current_settings.split("inet ")[1].split("/")[0] if "dhcp" in current_settings: config_type = "DHCP" elif ip_address: config_type = "Static" else: config_type = "Неизвестно" message = f"Тип настройки: {config_type}\nIP-адрес: {ip_address}" if ip_address else "IP-адрес не настроен" self.d.msgbox(f"Текущие настройки интерфейса {interface}:\n\n{message}", height=10, width=50) except subprocess.CalledProcessError as e: self.d.msgbox(f"Ошибка получения настроек для интерфейса {interface}: {e}") def configure_dhcp(self, interface): code, dns = self.d.inputbox("Введите DNS сервер (опционально):") if code == self.d.OK: self.temp_network_settings[interface] = { "type": "dhcp", "dns": dns, "interface": interface, } self.d.msgbox("DHCP настройка сохранена.") else: self.d.msgbox("DHCP настройка отменена.") def configure_static(self, interface): code, ip = self.d.inputbox("Введите IP адрес:") if code != self.d.OK: return code, mask = self.d.inputbox("Введите маску подсети:") if code != self.d.OK: return code, gateway = self.d.inputbox("Введите шлюз:") if code != self.d.OK: return code, dns = self.d.inputbox("Введите DNS сервер (опционально):") if ip and mask and gateway: self.temp_network_settings[interface] = { "type": "static", "ip": ip, "mask": mask, "gateway": gateway, "dns": dns, "interface": interface, } self.d.msgbox("Статические настройки сохранены.") else: self.d.msgbox("Некоторые параметры не заданы.") def configure_cidr(self, interface): code, cidr = self.d.inputbox("Введите CIDR (например, 192.168.1.154/24):") if code != self.d.OK: return code, gateway = self.d.inputbox("Введите шлюз:") if code != self.d.OK: return code, dns = self.d.inputbox("Введите DNS сервер (опционально):") if cidr: try: ip = ipaddress.ip_interface(cidr).ip network = ipaddress.ip_network(cidr, strict=False) mask = network.netmask self.temp_network_settings[interface] = { "type": "static", "ip": str(ip), "mask": str(mask), "gateway": gateway, "dns": dns, "interface": interface, } self.d.msgbox("CIDR конфигурация сохранена.") except ValueError as e: self.d.msgbox(f"Неверный формат CIDR: {e}") else: self.d.msgbox("CIDR не задан.") def run(self): while True: interface = self.select_interface() if not interface: break code, tag = self.d.menu( "Выберите действие для интерфейса:", choices=[ ("1", "Настроить DHCP"), ("2", "Настроить статический IP"), ("3", "Настроить CIDR"), ("4", "Выбрать другой интерфейс"), ("5", "Выход"), ], ) if code == self.d.OK: if tag == "1": self.configure_dhcp(interface) elif tag == "2": self.configure_static(interface) elif tag == "3": self.configure_cidr(interface) elif tag == "4": continue elif tag == "5": break else: break return self.temp_network_settings def save_and_apply_network_settings(self): for interface, settings in self.temp_network_settings.items(): try: if settings["type"] == "dhcp": self.save_dhcp(interface, settings) elif settings["type"] == "static": self.save_static(interface, settings) if settings.get("dns"): self.update_resolv_conf(settings["dns"]) except Exception as e: self.d.msgbox(f"Ошибка применения настроек для {interface}: {e}") return False try: subprocess.run(["systemctl", "restart", "networking"], check=True) self.d.msgbox("Сетевые настройки успешно применены.") return True except Exception as e: self.d.msgbox(f"Ошибка перезапуска сетевой службы: {e}") return False def save_dhcp(self, interface, settings): interface_config = f""" auto {interface} iface {interface} inet dhcp """ self.update_interface_config(interface, interface_config) def save_static(self, interface, settings): ip = settings["ip"] mask = settings["mask"] gateway = settings["gateway"] interface_config = f""" auto {interface} iface {interface} inet static address {ip} netmask {mask} """ if gateway: interface_config += f"gateway {gateway}\n" self.update_interface_config(interface, interface_config) def update_interface_config(self, interface, interface_config): try: with open("/etc/network/interfaces", "r") as f: lines = f.readlines() with open("/etc/network/interfaces", "w") as f: skip_section = False for line in lines: if interface in line: skip_section = True continue if skip_section and line.strip() == "": skip_section = False if not skip_section: f.write(line) f.write(interface_config.strip() + "\n") except Exception as e: self.d.msgbox(f"Ошибка обновления конфигурации интерфейса: {e}") def update_resolv_conf(self, dns): if not dns: return dns_entry = f"nameserver {dns}" try: with open("/etc/resolv.conf", "r") as f: resolv_lines = f.readlines() if any(line.strip() == dns_entry for line in resolv_lines): return with open("/etc/resolv.conf", "a") as f: f.write(dns_entry + "\n") except Exception as e: self.d.msgbox(f"Ошибка обновления /etc/resolv.conf: {e}") if __name__ == "__main__": configurator = NetworkConfig() configurator.run()