### List and Filter Network Devices Source: https://github.com/python-sdbus/python-sdbus-networkmanager/blob/master/docs/quickstart.rst This code example shows how to retrieve all network devices, identify their types (specifically filtering for Wi-Fi devices), and interact with device-specific properties using the python-sdbus library. It utilizes NetworkDeviceGeneric and NetworkDeviceWireless classes. ```python import sdbus from sdbus_block.networkmanager import ( NetworkDeviceGeneric, NetworkDeviceWireless, NetworkManager, ) from sdbus_block.networkmanager.enums import DeviceType sdbus.set_default_bus(sdbus.sd_bus_open_system()) network_manager = NetworkManager() all_devices = {path: NetworkDeviceGeneric(path) for path in network_manager.devices} wifi_devices = [ NetworkDeviceWireless(path) for path, device in all_devices.items() if device.device_type == DeviceType.WIFI ] ``` -------------------------------- ### Initialize NetworkManager D-Bus Connection Source: https://github.com/python-sdbus/python-sdbus-networkmanager/blob/master/docs/quickstart.rst This snippet demonstrates how to set up the default D-Bus connection to the system bus and initialize the NetworkManager object using python-sdbus. It's a foundational step for all subsequent NetworkManager operations. ```python import sdbus from sdbus_block.networkmanager import NetworkManager sdbus.set_default_bus(sdbus.sd_bus_open_system()) network_manager = NetworkManager() ``` -------------------------------- ### List Network Interfaces and IPv4 Addresses (Blocking Python) Source: https://github.com/python-sdbus/python-sdbus-networkmanager/blob/master/docs/examples.rst This snippet demonstrates how to list network device interfaces and their associated IPv4 addresses using the blocking API of python-sdbus with NetworkManager. It requires access to the system bus. ```python from sdbus_block.networkmanager import ( NetworkManager, NetworkDeviceGeneric, IPv4Config, ) from sdbus import sd_bus_open_system system_bus = sd_bus_open_system() # We need system bus nm = NetworkManager(system_bus) devices_paths = nm.get_devices() for device_path in devices_paths: generic_device = NetworkDeviceGeneric(device_path, system_bus) print('Device: ', generic_device.interface) device_ip4_conf_path = generic_device.ip4_config if device_ip4_conf_path == '/': # This is how NetworkManager indicates there is no ip config # for the interface continue else: ip4_conf = IPv4Config(device_ip4_conf_path, system_bus) for address_data in ip4_conf.address_data: print(' Ip Adress:', address_data['address'][1]) ``` -------------------------------- ### List Network Interfaces and IPv4 Addresses (Async Python) Source: https://github.com/python-sdbus/python-sdbus-networkmanager/blob/master/docs/examples.rst This snippet shows how to retrieve network device interfaces and their IPv4 addresses asynchronously using python-sdbus and NetworkManager. It leverages asyncio for non-blocking operations and requires the system bus. ```python from sdbus_async.networkmanager import ( NetworkManager, NetworkDeviceGeneric, IPv4Config, ) from sdbus import sd_bus_open_system from asyncio import run as async_run system_bus = sd_bus_open_system() # We need system bus nm = NetworkManager(system_bus) async def test() -> None: devices_paths = await nm.get_devices() for device_path in devices_paths: generic_device = NetworkDeviceGeneric(device_path, system_bus) print('Device: ', await generic_device.interface) device_ip4_conf_path = await generic_device.ip4_config if device_ip4_conf_path == '/': # This is how NetworkManager indicates there is no ip config # for the interface continue else: ip4_conf = IPv4Config(device_ip4_conf_path, system_bus) for address_data in await ip4_conf.address_data: print(' Ip Adress:', address_data['address'][1]) async_run(test()) ``` -------------------------------- ### Manage Network Connection Profiles Source: https://github.com/python-sdbus/python-sdbus-networkmanager/blob/master/docs/quickstart.rst This snippet illustrates how to access and retrieve connection profiles using the NetworkManagerSettings and NetworkConnectionSettings classes from python-sdbus. It demonstrates fetching a specific connection's profile settings, including its UUID. ```python import sdbus from sdbus_block.networkmanager import ( NetworkConnectionSettings, NetworkManager, NetworkManagerSettings, ) sdbus.set_default_bus(sdbus.sd_bus_open_system()) network_manager = NetworkManager() networwork_manager_settings = NetworkManagerSettings() connection = NetworkConnectionSettings(networwork_manager_settings.connections[0]) setting_dataclass = connection.get_profile() print("uuid:", setting_dataclass.connection.uuid) ``` -------------------------------- ### List Connection Profiles Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt Retrieve and display all saved connection profiles with their configuration details. ```APIDOC ## List Connection Profiles ### Description Retrieve and display all saved connection profiles with their configuration details. ### Method GET (Implicit via D-Bus calls) ### Endpoint NetworkManagerSettings D-Bus Interface ### Parameters None ### Request Example ```python import asyncio import sdbus from sdbus_async.networkmanager import ( NetworkManagerSettings, NetworkConnectionSettings, ) async def list_connections(): """List all connection profiles with details""" sdbus.set_default_bus(sdbus.sd_bus_open_system()) settings = NetworkManagerSettings() connection_paths = await settings.connections for path in connection_paths: try: conn = NetworkConnectionSettings(path) profile = await conn.get_profile() print(f"\n{'='*60}") print(f"Name: {profile.connection.connection_id}") print(f"UUID: {profile.connection.uuid}") print(f"Type: {profile.connection.connection_type}") if profile.connection.interface_name: print(f"Interface: {profile.connection.interface_name}") if profile.ipv4: print(f"IPv4 Method: {profile.ipv4.method}") if profile.ipv4.address_data: for addr in profile.ipv4.address_data: print(f" Address: {addr.address}/{addr.prefix}") if profile.ipv4.route_metric: print(f" Route Metric: {profile.ipv4.route_metric}") if profile.ipv6: print(f"IPv6 Method: {profile.ipv6.method}") except Exception as e: print(f"Error reading connection {path}: {e}") if __name__ == "__main__": asyncio.run(list_connections()) ``` ### Response #### Success Response (200) - **List of connection profiles**: Each profile includes its name, UUID, type, interface name, and IPv4/IPv6 configuration details. #### Response Example ```text ============================================================ Name: Wired connection 1 UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx Type: ethernet Interface: enp0s31f6 IPv4 Method: auto Address: 192.168.1.100/24 Route Metric: 100 ============================================================ Name: My WiFi Network UUID: yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy Type: wifi Interface: wlp0s20f3 IPv4 Method: auto ``` ``` -------------------------------- ### List Network Connections (Blocking API) Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt This Python script demonstrates how to list all network connections using the synchronous blocking API provided by python-sdbus. It sets the default D-Bus connection to the system bus and iterates through NetworkManager settings to retrieve and print connection details like name, UUID, and type. No external dependencies are required beyond the python-sdbus library. ```python #!/usr/bin/env python import sdbus from sdbus_block.networkmanager import ( NetworkManager, NetworkManagerSettings, NetworkConnectionSettings, NetworkDeviceGeneric, DeviceState, ) def list_connections_blocking(): """List all connections using blocking API""" sdbus.set_default_bus(sdbus.sd_bus_open_system()) settings = NetworkManagerSettings() for conn_path in settings.connections: conn = NetworkConnectionSettings(conn_path) profile = conn.get_profile() print(f"\nName: {profile.connection.connection_id}") print(f"UUID: {profile.connection.uuid}") print(f"Type: {profile.connection.connection_type}") if __name__ == "__main__": list_connections_blocking() ``` -------------------------------- ### List Network Devices and States Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt Query all network devices including their type, state, connectivity, and active connections. ```APIDOC ## List Network Devices and States ### Description Query all network devices including their type, state, connectivity, and active connections. ### Method GET (Implicit via D-Bus calls) ### Endpoint NetworkManager D-Bus Interface ### Parameters None ### Request Example ```python import asyncio import sdbus from sdbus_async.networkmanager import ( NetworkManager, NetworkDeviceGeneric, DeviceState, DeviceType, ActiveConnection, ConnectivityState, ) async def list_devices(): """List all network devices with their state and connectivity""" sdbus.set_default_bus(sdbus.sd_bus_open_system()) nm = NetworkManager() devices_paths = await nm.get_devices() print("Interface Type State Internet Connection") for device_path in devices_paths: try: device = NetworkDeviceGeneric(device_path) interface = await device.interface device_type = DeviceType(await device.device_type).name.title() state = DeviceState(await device.state).name.title() connectivity = ConnectivityState(await device.ip4_connectivity).name.title() connection_name = "" if await device.active_connection != "/": active_conn = ActiveConnection(await device.active_connection) connection_name = await active_conn.id if await active_conn.default: connection_name += " [primary]" print(f"{interface:<17} {device_type:<8} {state:<12} {connectivity:<8} {connection_name}") except Exception as e: print(f"Error reading device {device_path}: {e}") if __name__ == "__main__": asyncio.run(list_devices()) ``` ### Response #### Success Response (200) - **List of devices**: Each device is represented by its interface name, type, state, IP connectivity, and active connection name. #### Response Example ```text Interface Type State Internet Connection lo Generic Unmanaged Unknown wlp0s20f3 Wifi Activated Full HomeWiFi [primary] enp0s31f6 Ethernet Unavailable None ``` ``` -------------------------------- ### List Connection Profiles with python-sdbus Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt Retrieves and displays all saved network connection profiles along with their configuration details, such as name, UUID, type, and IP settings. This function relies on the python-sdbus library and the 'sdbus_async.networkmanager' module. ```python #!/usr/bin/env python import asyncio import sdbus from sdbus_async.networkmanager import ( NetworkManagerSettings, NetworkConnectionSettings, ) async def list_connections(): """List all connection profiles with details""" sdbus.set_default_bus(sdbus.sd_bus_open_system()) settings = NetworkManagerSettings() connection_paths = await settings.connections for path in connection_paths: try: conn = NetworkConnectionSettings(path) profile = await conn.get_profile() print(f"\n{'='*60}") print(f"Name: {profile.connection.connection_id}") print(f"UUID: {profile.connection.uuid}") print(f"Type: {profile.connection.connection_type}") if profile.connection.interface_name: print(f"Interface: {profile.connection.interface_name}") if profile.ipv4: print(f"IPv4 Method: {profile.ipv4.method}") if profile.ipv4.address_data: for addr in profile.ipv4.address_data: print(f" Address: {addr.address}/{addr.prefix}") if profile.ipv4.route_metric: print(f" Route Metric: {profile.ipv4.route_metric}") if profile.ipv6: print(f"IPv6 Method: {profile.ipv6.method}") except Exception as e: print(f"Error reading connection {path}: {e}") if __name__ == "__main__": asyncio.run(list_connections()) ``` -------------------------------- ### List Network Devices and States with python-sdbus Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt Queries and displays all network devices, including their type, state, connectivity, and active connection names. It uses the python-sdbus library to interact with the NetworkManager D-Bus interface. This function requires the 'sdbus' library and the 'sdbus_async.networkmanager' module. ```python #!/usr/bin/env python import asyncio import sdbus from sdbus_async.networkmanager import ( NetworkManager, NetworkDeviceGeneric, DeviceState, DeviceType, ActiveConnection, ConnectivityState, ) async def list_devices(): """List all network devices with their state and connectivity""" sdbus.set_default_bus(sdbus.sd_bus_open_system()) nm = NetworkManager() devices_paths = await nm.get_devices() print("Interface Type State Internet Connection") for device_path in devices_paths: try: device = NetworkDeviceGeneric(device_path) interface = await device.interface device_type = DeviceType(await device.device_type).name.title() state = DeviceState(await device.state).name.title() connectivity = ConnectivityState(await device.ip4_connectivity).name.title() connection_name = "" if await device.active_connection != "/": active_conn = ActiveConnection(await device.active_connection) connection_name = await active_conn.id if await active_conn.default: connection_name += " [primary]" print(f"{interface:<17} {device_type:<8} {state:<12} {connectivity:<8} {connection_name}") except Exception as e: print(f"Error reading device {device_path}: {e}") if __name__ == "__main__": asyncio.run(list_devices()) # Example output: # Interface Type State Internet Connection # lo Generic Unmanaged Unknown # wlp0s20f3 Wifi Activated Full HomeWiFi [primary] # enp0s31f6 Ethernet Unavailable None ``` -------------------------------- ### Monitor Network Device State Changes with Python sdbus Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt This snippet shows how to monitor a network device for changes in its state and connectivity using the python-sdbus library. It subscribes to D-Bus signals emitted by NetworkManager. Dependencies include 'sdbus' and 'sdbus-async'. The input is an interface name, and the output consists of print statements detailing state transitions and connectivity events. ```python #!/usr/bin/env python import asyncio import sdbus from sdbus_async.networkmanager import ( NetworkManager, NetworkDeviceGeneric, DeviceState, ConnectivityState, ) async def monitor_device_changes(interface_name="wlan0"): """Monitor a network device for state changes Args: interface_name: Network interface to monitor """ sdbus.set_default_bus(sdbus.sd_bus_open_system()) nm = NetworkManager() # Get device by interface name device_path = await nm.get_device_by_ip_iface(interface_name) device = NetworkDeviceGeneric(device_path) print(f"Monitoring device: {interface_name}") print(f"D-Bus path: {device_path}") # Get initial state initial_state = DeviceState(await device.state) print(f"Initial state: {initial_state.name}") # Subscribe to PropertiesChanged signal async for member, changed_properties, invalidated in device.properties_changed: for prop_name, prop_value in changed_properties.items(): if prop_name == "State": new_state = DeviceState(prop_value[1]) print(f"State changed: {new_state.name}") elif prop_name == "Ip4Connectivity": connectivity = ConnectivityState(prop_value[1]) print(f"IPv4 connectivity: {connectivity.name}") elif prop_name == "ActiveConnection": conn_path = prop_value[1] print(f"Active connection changed: {conn_path}") if __name__ == "__main__": try: asyncio.run(monitor_device_changes("wlan0")) except KeyboardInterrupt: print("\nMonitoring stopped") ``` -------------------------------- ### Create WiFi PSK Connection with Python sdbus Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt This function adds a new Wi-Fi connection profile to NetworkManager. It supports WPA-PSK authentication by hashing the provided password if it's shorter than 64 characters. The connection can be saved permanently or created as an in-memory-only profile. It requires the `sdbus-async` library and `passlib` for password hashing. ```python #!/usr/bin/env python import asyncio import binascii import sdbus from uuid import uuid4 from passlib.utils.pbkdf2 import pbkdf2 from sdbus_async.networkmanager import ( NetworkManagerSettings, ConnectionType, ) from sdbus_async.networkmanager.settings import ( ConnectionProfile, ConnectionSettings, Ipv4Settings, Ipv6Settings, WirelessSettings, WirelessSecuritySettings, ) async def add_wifi_connection(ssid, password, connection_id="MyWiFi", autoconnect=True, save=False): """Create a new WiFi connection profile Args: ssid: WiFi network name password: WiFi password (will be hashed to PSK) connection_id: Name for the connection profile autoconnect: Whether to connect automatically save: If True, save permanently; if False, create in-memory only Returns: D-Bus path of the created connection """ sdbus.set_default_bus(sdbus.sd_bus_open_system()) settings_manager = NetworkManagerSettings() # Check if connection already exists existing = await settings_manager.get_connections_by_id(connection_id) if existing: raise ValueError(f"Connection '{connection_id}' already exists") # Hash password to PSK if needed if len(password) < 64: pw_hash = pbkdf2(password.encode(), ssid.encode(), 4096, 32) psk = binascii.hexlify(pw_hash).decode("utf-8") else: psk = password # Create connection profile profile = ConnectionProfile( connection=ConnectionSettings( connection_id=connection_id, uuid=str(uuid4()), connection_type=ConnectionType.WIFI.value, autoconnect=autoconnect, ), ipv4=Ipv4Settings(method="auto"), ipv6=Ipv6Settings(method="auto"), wireless=WirelessSettings(ssid=ssid.encode("utf-8")), wireless_security=WirelessSecuritySettings( key_mgmt="wpa-psk", auth_alg="open", psk=psk ), ) # Add connection (saved or unsaved) add_method = settings_manager.add_connection if save else settings_manager.add_connection_unsaved connection_path = await add_method(profile.to_dbus()) print(f"Created connection: {connection_id}") print(f"D-Bus path: {connection_path}") return connection_path if __name__ == "__main__": # Example: Create unsaved WiFi connection asyncio.run(add_wifi_connection( ssid="CoffeeShop", password="SecurePassword123", connection_id="CoffeeShop-WiFi", autoconnect=False, save=False )) ``` -------------------------------- ### Using Python Enums for Device Types and WiFi Capabilities Source: https://github.com/python-sdbus/python-sdbus-networkmanager/blob/master/docs/enums.rst Demonstrates how to use IntEnum for discrete values like DeviceType and IntFlag for bit flags like WifiCapabilitiesFlags. Shows how to create enum instances from integers and check for specific flags. ```python from sdbus_async.networkmanager.enums import DeviceType, WifiCapabilitiesFlags # Get particular device type from an integer DeviceType(2) == DeviceType.WIFI # Returns: True # Check if a specific flag is enabled WifiCapabilitiesFlags.FREQ_2GHZ in WifiCapabilitiesFlags(0x00000400 | 0x00000200) # Returns: True # Iterate over all enabled flags list(WifiCapabilitiesFlags(0x00000400 | 0x00000200)) # Returns: [, ] ``` -------------------------------- ### List WiFi Access Points with Python sdbus Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt Scans for and lists available WiFi networks, displaying their SSID, signal strength, frequency, and security type. It requires the 'sdbus' and 'sdbus-async' libraries. The function takes an optional interface name (defaulting to 'wlan0') and returns no explicit value, but prints the network information. ```python #!/usr/bin/env python import asyncio import sdbus from sdbus_async.networkmanager import ( NetworkManager, NetworkDeviceWireless, AccessPoint, WifiAccessPointSecurityFlags, ) async def list_wifi_networks(interface="wlan0"): """List available WiFi networks Args: interface: WiFi interface name """ sdbus.set_default_bus(sdbus.sd_bus_open_system()) nm = NetworkManager() # Get WiFi device device_path = await nm.get_device_by_ip_iface(interface) wifi_device = NetworkDeviceWireless(device_path) # Request scan await wifi_device.request_scan({}) await asyncio.sleep(3) # Wait for scan to complete # Get access points ap_paths = await wifi_device.access_points print(f"{'SSID':<32} {'Signal':<8} {'Frequency':<10} {'Security'}") print("=" * 80) for ap_path in ap_paths: try: ap = AccessPoint(ap_path) ssid_bytes = await ap.ssid ssid = ssid_bytes.decode('utf-8', errors='replace') signal = await ap.strength frequency = await ap.frequency # Check security wpa_flags = await ap.wpa_flags rsn_flags = await ap.rsn_flags if wpa_flags or rsn_flags: security = "WPA/WPA2" else: security = "Open" print(f"{ssid:<32} {signal:>3}% {frequency:<10} {security}") except Exception as e: print(f"Error reading AP {ap_path}: {e}") if __name__ == "__main__": asyncio.run(list_wifi_networks("wlan0")) # Example output: # SSID Signal Frequency Security # ================================================================= ================ # HomeNetwork 95% 5220 WPA/WPA2 # CoffeeShop-Guest 72% 2437 Open # Office-5G 45% 5180 WPA/WPA2 ``` -------------------------------- ### Check Network Device State (Blocking API) Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt This Python script shows how to check the state of a network device using the blocking API of python-sdbus. It takes an interface name (e.g., 'eth0') as input, retrieves the device path from NetworkManager, and then fetches the device's current state. It also checks if an active connection exists and prints the IPv4 configuration path if available. This function is useful for monitoring network interface status. ```python #!/usr/bin/env python import sdbus from sdbus_block.networkmanager import ( NetworkManager, NetworkManagerSettings, NetworkConnectionSettings, NetworkDeviceGeneric, DeviceState, ) def check_device_state_blocking(interface="eth0"): """Check device state using blocking API""" sdbus.set_default_bus(sdbus.sd_bus_open_system()) nm = NetworkManager() device_path = nm.get_device_by_ip_iface(interface) device = NetworkDeviceGeneric(device_path) state = DeviceState(device.state) print(f"Device {interface} state: {state.name}") if device.active_connection != "/": # Device has active connection ip4_config = device.ip4_config print(f"IPv4 config path: {ip4_config}") if __name__ == "__main__": check_device_state_blocking("eth0") ``` -------------------------------- ### Update Network Connection Settings with Python sdbus Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt This snippet demonstrates how to modify existing network connection profiles using the python-sdbus library. It allows updating IP addresses and autoconnect settings. Dependencies include the 'sdbus' and 'sdbus-async' libraries. Inputs are the connection UUID and optional new IP/autoconnect values. Outputs include a confirmation message upon successful update. Note: Direct modification of settings requires careful handling of D-Bus types. ```python #!/usr/bin/env python import asyncio import sdbus from sdbus_async.networkmanager import ( NetworkManagerSettings, NetworkConnectionSettings, ) async def update_connection(connection_uuid, new_ip=None, new_autoconnect=None): """Update connection settings Args: connection_uuid: UUID of connection to update new_ip: New IP address (optional) new_autoconnect: New autoconnect value (optional) """ sdbus.set_default_bus(sdbus.sd_bus_open_system()) settings = NetworkManagerSettings() # Get connection path and settings conn_path = await settings.get_connection_by_uuid(connection_uuid) conn = NetworkConnectionSettings(conn_path) # Get current settings current_settings = await conn.get_settings() # Modify settings if new_autoconnect is not None: current_settings["connection"]["autoconnect"] = ("b", new_autoconnect) if new_ip is not None: ip_addr, prefix = new_ip.split("/") current_settings["ipv4"]["address-data"] = ( "aa{sv}", [{"address": ("s", ip_addr), "prefix": ("u", int(prefix))}] ) # Update the connection await conn.update(current_settings) print(f"Updated connection: {connection_uuid}") # Example with ConnectionProfile high-level API async def update_connection_profile(connection_uuid): """Update using high-level ConnectionProfile API""" sdbus.set_default_bus(sdbus.sd_bus_open_system()) settings = NetworkManagerSettings() # Get connection and profile conn_path = await settings.get_connection_by_uuid(connection_uuid) conn = NetworkConnectionSettings(conn_path) profile = await conn.get_profile() # Modify profile profile.connection.autoconnect = False if profile.ipv4: profile.ipv4.method = "auto" # Change from manual to DHCP # Save changes await conn.update(profile.to_dbus()) print(f"Updated profile: {profile.connection.connection_id}") if __name__ == "__main__": asyncio.run( update_connection( "90e3bcc8-d3a5-4725-a363-abb788fd47bf", new_ip="192.168.1.150/24", new_autoconnect=True ) ) ``` -------------------------------- ### Create Ethernet Connection with Static IP using Python sdbus Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt This function adds a new Ethernet connection profile to NetworkManager. It allows specifying details like connection name, interface, IP address, gateway, and autoconnect settings. The connection can be saved permanently or created in-memory only. It requires the 'sdbus-async' library and uses asyncio for asynchronous operations. ```python #!/usr/bin/env python import asyncio import sdbus from uuid import uuid4 from sdbus_async.networkmanager import ( NetworkManagerSettings, NetworkManagerConnectionProperties, ) async def add_ethernet_connection( connection_id="MyEthernet", interface="eth0", ip_address="192.168.1.100", prefix=24, gateway="192.168.1.1", route_metric=100, autoconnect=True, save=False ): """Create an Ethernet connection with static IP Args: connection_id: Name for the connection interface: Network interface name (e.g., 'eth0', 'enp0s3') ip_address: Static IP address prefix: Network prefix length (e.g., 24 for /24) gateway: Default gateway IP route_metric: Route metric/priority autoconnect: Auto-connect on boot save: Save permanently or create in-memory only Returns: D-Bus path of created connection """ sdbus.set_default_bus(sdbus.sd_bus_open_system()) settings = NetworkManagerSettings() # Check for existing connections if await settings.get_connections_by_id(connection_id): raise ValueError(f"Connection '{connection_id}' already exists") # Define connection properties using low-level D-Bus format properties: NetworkManagerConnectionProperties = { "connection": { "id": ("s", connection_id), "uuid": ("s", str(uuid4())), "type": ("s", "802-3-ethernet"), "autoconnect": ("b", autoconnect), "interface-name": ("s", interface), }, "ipv4": { "method": ("s", "manual"), "address-data": ( "aa{sv}", [ { "address": ("s", ip_address), "prefix": ("u", prefix), }, ], ), "gateway": ("s", gateway), "route-metric": ("u", route_metric), }, "ipv6": { "method": ("s", "disabled") }, } # Add connection add_func = settings.add_connection if save else settings.add_connection_unsaved connection_path = await add_func(properties) print(f"Created Ethernet connection: {connection_id}") print(f"Configuration: {ip_address}/{prefix} via {gateway}") print(f"D-Bus path: {connection_path}") return connection_path if __name__ == "__main__": asyncio.run(add_ethernet_connection( connection_id="Office-LAN", interface="enp0s3", ip_address="192.168.100.50", prefix=24, gateway="192.168.100.1", route_metric=200, autoconnect=True, save=False )) ``` -------------------------------- ### Activate/Deactivate Network Connections with Python sdbus Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt Manages the activation and deactivation of network connection profiles using the NetworkManager D-Bus interface via the 'sdbus' library. It requires 'sdbus' and 'sdbus-async'. Functions include activating a connection by UUID and interface, deactivating by active connection path, and deactivating by UUID. These operations modify the system's network state. ```python #!/usr/bin/env python import asyncio import sdbus from sdbus_async.networkmanager import ( NetworkManager, NetworkManagerSettings, ActiveConnection, ) async def activate_connection(connection_uuid, interface=None): """Activate a connection profile Args: connection_uuid: UUID of connection to activate interface: Device path or '/' for any device """ sdbus.set_default_bus(sdbus.sd_bus_open_system()) nm = NetworkManager() settings = NetworkManagerSettings() # Get connection path conn_path = await settings.get_connection_by_uuid(connection_uuid) # Determine device device_path = "/" if interface: device_path = await nm.get_device_by_ip_iface(interface) # Activate connection active_conn_path = await nm.activate_connection(conn_path, device_path, "/") print(f"Activated connection: {connection_uuid}") print(f"Active connection path: {active_conn_path}") return active_conn_path async def deactivate_connection(active_connection_path): """Deactivate an active connection Args: active_connection_path: D-Bus path of active connection """ sdbus.set_default_bus(sdbus.sd_bus_open_system()) nm = NetworkManager() await nm.deactivate_connection(active_connection_path) print(f"Deactivated connection: {active_connection_path}") async def deactivate_connection_by_uuid(connection_uuid): """Find and deactivate a connection by its UUID""" sdbus.set_default_bus(sdbus.sd_bus_open_system()) nm = NetworkManager() settings = NetworkManagerSettings() # Get connection path conn_path = await settings.get_connection_by_uuid(connection_uuid) # Find active connection active_connections = await nm.active_connections for ac_path in active_connections: ac = ActiveConnection(ac_path) if await ac.connection == conn_path: await nm.deactivate_connection(ac_path) print(f"Deactivated connection: {connection_uuid}") return print(f"Connection not active: {connection_uuid}") if __name__ == "__main__": # Activate a connection active_path = asyncio.run(activate_connection( "90e3bcc8-d3a5-4725-a363-abb788fd47bf", interface="wlan0" )) # Wait a bit asyncio.run(asyncio.sleep(5)) # Deactivate it asyncio.run(deactivate_connection(active_path)) ``` -------------------------------- ### Delete Network Connection by UUID using Python sdbus Source: https://context7.com/python-sdbus/python-sdbus-networkmanager/llms.txt This function removes a NetworkManager connection profile using its unique UUID. It first retrieves the D-Bus path of the connection based on the provided UUID and then calls the delete method on the connection object. An alternative function is provided to delete connections by their name (ID). Both functions utilize asyncio and the 'sdbus-async' library. ```python #!/usr/bin/env python import asyncio import sdbus from sdbus_async.networkmanager import ( NetworkManagerSettings, NetworkConnectionSettings, ) async def delete_connection(connection_uuid): """Delete a connection profile by UUID Args: connection_uuid: UUID of the connection to delete """ sdbus.set_default_bus(sdbus.sd_bus_open_system()) settings = NetworkManagerSettings() try: # Get connection D-Bus path from UUID connection_path = await settings.get_connection_by_uuid(connection_uuid) # Delete the connection conn = NetworkConnectionSettings(connection_path) await conn.delete() print(f"Successfully deleted connection: {connection_uuid}") except Exception as e: print(f"Error deleting connection: {e}") raise # Alternative: Delete by connection ID (name) async def delete_connections_by_id(connection_id): """Delete all connections with given ID/name""" sdbus.set_default_bus(sdbus.sd_bus_open_system()) settings = NetworkManagerSettings() connection_paths = await settings.get_connections_by_id(connection_id) if not connection_paths: print(f"No connections found with ID: {connection_id}") return for path in connection_paths: conn = NetworkConnectionSettings(path) await conn.delete() print(f"Deleted connection: {path}") if __name__ == "__main__": # Delete by UUID asyncio.run(delete_connection("b2caabdc-98bb-3f88-8d28-d10369d6ded9")) # Or delete by name # asyncio.run(delete_connections_by_id("MyWiFi")) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.