#!/usr/bin/env python3 """Сводка по сетевым интерфейсам Linux через ip -j.""" from __future__ import annotations import argparse import json import shutil import subprocess from dataclasses import asdict, dataclass from pathlib import Path @dataclass class Interface: name: str state: str mtu: int | None mac: str addresses: list[str] rx_bytes: int tx_bytes: int rx_errors: int tx_errors: int rx_dropped: int tx_dropped: int default_route: bool def ip_json(args: list[str]) -> list[dict]: result = subprocess.run(["ip", "-j", *args], capture_output=True, text=True, check=False) if result.returncode != 0 or not result.stdout.strip(): return [] try: data = json.loads(result.stdout) except json.JSONDecodeError: return [] return data if isinstance(data, list) else [] def read_number(path: Path) -> int: try: return int(path.read_text(encoding="utf-8").strip()) except (OSError, ValueError): return 0 def human(value: int) -> str: size = float(value) for unit in ("B", "KiB", "MiB", "GiB", "TiB"): if size < 1024 or unit == "TiB": return f"{size:.1f} {unit}" size /= 1024 return f"{value} B" def main() -> int: parser = argparse.ArgumentParser(description="Сводка по сети Linux") parser.add_argument("--interface", help="Показать только этот интерфейс") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() if shutil.which("ip") is None: print("ip не найден. Установите iproute2.") return 2 links = {item.get("ifname"): item for item in ip_json(["link", "show"]) if item.get("ifname")} addresses = ip_json(["addr", "show"]) routes = ip_json(["route", "show"]) neighbors = ip_json(["neigh", "show"]) default_devices = {item.get("dev") for item in routes if item.get("dst") == "default"} result: list[Interface] = [] for item in addresses: name = item.get("ifname") if not name: continue if args.interface and name != args.interface: continue link = links.get(name, {}) stats = Path("/sys/class/net") / name / "statistics" addr_list = [] for address in item.get("addr_info", []): local = address.get("local") prefix = address.get("prefixlen") if local: addr_list.append(f"{local}/{prefix}" if prefix is not None else str(local)) result.append( Interface( name=name, state=str(link.get("operstate", "unknown")), mtu=link.get("mtu"), mac=str(link.get("address", "-")), addresses=addr_list, rx_bytes=read_number(stats / "rx_bytes"), tx_bytes=read_number(stats / "tx_bytes"), rx_errors=read_number(stats / "rx_errors"), tx_errors=read_number(stats / "tx_errors"), rx_dropped=read_number(stats / "rx_dropped"), tx_dropped=read_number(stats / "tx_dropped"), default_route=name in default_devices, ) ) result.sort(key=lambda item: item.name) print(f"{'ИНТЕРФЕЙС':<16} {'СОСТОЯНИЕ':<12} {'MTU':>6} {'АДРЕСА':<34} {'RX':>10} {'TX':>10} {'ОШИБКИ':>7} DEFAULT") print("-" * 110) for item in result: errors = item.rx_errors + item.tx_errors + item.rx_dropped + item.tx_dropped print( f"{item.name:<16} {item.state:<12} {str(item.mtu or '-'):>6} " f"{','.join(item.addresses)[:34]:<34} {human(item.rx_bytes):>10} {human(item.tx_bytes):>10} {errors:>7} " f"{'да' if item.default_route else 'нет'}" ) print("\nМаршруты по умолчанию:") for route in routes: if route.get("dst") == "default": print(f" via {route.get('gateway', '-')} dev {route.get('dev', '-')} metric {route.get('metric', '-')}") if not any(route.get("dst") == "default" for route in routes): print(" не найдены") resolv = Path("/etc/resolv.conf") print("\nDNS:") if resolv.is_file(): for line in resolv.read_text(encoding="utf-8", errors="replace").splitlines(): if line.startswith(("nameserver", "search", "domain")): print(f" {line}") else: print(" /etc/resolv.conf не найден") print(f"\nСоседей в таблице: {len(neighbors)}") if args.json: args.json.write_text( json.dumps({"interfaces": [asdict(item) for item in result], "routes": routes, "neighbors": neighbors}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"JSON сохранён: {args.json}") return 0 if __name__ == "__main__": raise SystemExit(main())