#!/usr/bin/env python3 """Текущее Wi-Fi подключение macOS без сторонних утилит.""" from __future__ import annotations import argparse import json import re import subprocess from pathlib import Path def run(command: list[str]) -> str: result = subprocess.run(command, capture_output=True, text=True, check=False) return result.stdout def wifi_interface() -> str: output = run(["networksetup", "-listallhardwareports"]) blocks = output.split("\n\n") for block in blocks: if "Wi-Fi" in block or "AirPort" in block: match = re.search(r"Device:\s*(\S+)", block) if match: return match.group(1) return "en0" def find_network(node): if isinstance(node, dict): if any(key.startswith("spairport_network_") for key in node): return node for value in node.values(): found = find_network(value) if found: return found elif isinstance(node, list): for item in node: found = find_network(item) if found: return found return {} def current_network() -> dict: output = run(["system_profiler", "SPAirPortDataType", "-json"]) try: data = json.loads(output) except json.JSONDecodeError: return {} return find_network(data) def gateway() -> str: output = run(["route", "-n", "get", "default"]) match = re.search(r"gateway:\s*(\S+)", output) return match.group(1) if match else "" def main() -> int: parser = argparse.ArgumentParser(description="Показать информацию о Wi-Fi") parser.add_argument("--json", type=Path) args = parser.parse_args() interface = wifi_interface() ip_address = run(["ipconfig", "getifaddr", interface]).strip() network = current_network() report = { "interface": interface, "ip": ip_address, "gateway": gateway(), "ssid": network.get("spairport_network_ssid", ""), "channel": network.get("spairport_network_channel", ""), "security": network.get("spairport_network_security", ""), "signal_noise": network.get("spairport_signal_noise", ""), "rate": network.get("spairport_network_rate", ""), "country": network.get("spairport_network_country_code", ""), } if args.json: args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Интерфейс: {interface}") if not report["ssid"] and not ip_address: print("Wi-Fi не подключён или данные недоступны.") return 0 print(f"SSID: {report['ssid'] or 'скрыто или неизвестно'}") print(f"IP: {ip_address or 'нет'}") print(f"Маршрутизатор: {report['gateway'] or 'не определён'}") print(f"Канал: {report['channel'] or 'неизвестно'}") print(f"Безопасность: {report['security'] or 'неизвестно'}") print(f"Сигнал/шум: {report['signal_noise'] or 'неизвестно'}") print(f"Скорость: {report['rate'] or 'неизвестно'}") if report["country"]: print(f"Страна: {report['country']}") return 0 if __name__ == "__main__": raise SystemExit(main())