|
| 1 | +#!/usr/bin/env python |
| 2 | +# SPDX-License-Identifier: LGPL-2.1-or-later |
| 3 | +# |
| 4 | +# Example to list the active IPv4 protocol configuration of network devices |
| 5 | +# and the current status of WiFi adapters |
| 6 | +# |
| 7 | +# For IPv4 and org.freedesktop.NetworkManager.Device.Wireless see: |
| 8 | +# https://networkmanager.dev/docs/api/latest/settings-ipv4.html |
| 9 | +# https://networkmanager.dev/docs/api/latest/ref-dbus-devices.html |
| 10 | +import asyncio |
| 11 | +import sdbus |
| 12 | +from sdbus_async.networkmanager import ( |
| 13 | + NetworkManager, |
| 14 | + NetworkDeviceGeneric, |
| 15 | + IPv4Config, |
| 16 | + DeviceType, |
| 17 | + NetworkDeviceWireless, |
| 18 | + WiFiOperationMode, |
| 19 | + AccessPoint, |
| 20 | +) |
| 21 | +from typing import Any, Dict, List, Tuple |
| 22 | +NetworkManagerAddressData = List[Dict[str, Tuple[str, Any]]] |
| 23 | + |
| 24 | + |
| 25 | +async def list_networkdevice_details_async() -> None: |
| 26 | + nm = NetworkManager() |
| 27 | + devices_paths = await nm.get_devices() |
| 28 | + |
| 29 | + for device_path in devices_paths: |
| 30 | + generic_device = NetworkDeviceGeneric(device_path) |
| 31 | + device_ip4_conf_path: str = await generic_device.ip4_config |
| 32 | + if device_ip4_conf_path == "/": |
| 33 | + continue |
| 34 | + |
| 35 | + ip4_conf = IPv4Config(device_ip4_conf_path) |
| 36 | + gateway: str = await ip4_conf.gateway |
| 37 | + |
| 38 | + print("Device: ", await generic_device.interface) |
| 39 | + if gateway: |
| 40 | + print("Gateway:", gateway) |
| 41 | + |
| 42 | + address_data: NetworkManagerAddressData = await ip4_conf.address_data |
| 43 | + for inetaddr in address_data: |
| 44 | + print(f'Address: {inetaddr["address"][1]}/{inetaddr["prefix"][1]}') |
| 45 | + |
| 46 | + nameservers: NetworkManagerAddressData = await ip4_conf.nameserver_data |
| 47 | + for dns in nameservers: |
| 48 | + print("DNS: ", dns["address"][1]) |
| 49 | + |
| 50 | + if await generic_device.device_type == DeviceType.WIFI: |
| 51 | + wifi = NetworkDeviceWireless(device_path) |
| 52 | + print("Wifi: ", WiFiOperationMode(await wifi.mode).name.title()) |
| 53 | + ap = AccessPoint(await wifi.active_access_point) |
| 54 | + ssid: bytes = await ap.ssid |
| 55 | + if ssid: |
| 56 | + print("SSID: ", ssid.decode("utf-8", "ignore")) |
| 57 | + if await ap.strength: |
| 58 | + print("Signal: ", await ap.strength) |
| 59 | + |
| 60 | + print("") |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + sdbus.set_default_bus(sdbus.sd_bus_open_system()) |
| 65 | + asyncio.run(list_networkdevice_details_async()) |
0 commit comments