|
| 1 | +#!/usr/bin/env python |
| 2 | +# SPDX-License-Identifier: LGPL-2.1-or-later |
| 3 | +# |
| 4 | +# Update a property of a connection profile, looked up by connection id |
| 5 | +# |
| 6 | +# The IPv4 settings of connections profiles are documented here: |
| 7 | +# https://networkmanager.dev/docs/api/latest/settings-ipv4.html |
| 8 | +# |
| 9 | +import asyncio |
| 10 | +import sdbus |
| 11 | +from functools import partial |
| 12 | +from sdbus_async.networkmanager import NetworkManagerSettings |
| 13 | +from sdbus_async.networkmanager import NetworkConnectionSettings |
| 14 | +from pprint import pprint |
| 15 | +from typing import Any, Dict |
| 16 | + |
| 17 | + |
| 18 | +async def update_connection_async(args: Dict[str, Any]) -> None: |
| 19 | + """Update the settings for [key][entry] of the 1st matching connection""" |
| 20 | + fn = NetworkManagerSettings().get_connections_by_id(args["connection_id"]) |
| 21 | + connection_paths = await fn |
| 22 | + settings_domain, setting = args["connection_setting"] |
| 23 | + if connection_paths: |
| 24 | + connection_settings = NetworkConnectionSettings(connection_paths[0]) |
| 25 | + properties = await connection_settings.get_settings() |
| 26 | + # For compatibility with old tools, NM adds and prefers them, delete: |
| 27 | + properties["ipv4"].pop("addresses") # -> Use ["ipv4"]["address-data"] |
| 28 | + properties["ipv4"].pop("routes") # ----> Use ["ipv4"]["route-data"] |
| 29 | + |
| 30 | + # Update the setting's value in the given configuration group: |
| 31 | + properties[settings_domain][setting] = args["value"] |
| 32 | + await connection_settings.update(properties) |
| 33 | + |
| 34 | + print(f'Updated {properties["connection"]["uuid"]}.{settings_domain}:') |
| 35 | + partial(pprint, sort_dicts=False)(properties[settings_domain]) |
| 36 | + else: |
| 37 | + print(f"No connection matching {id}") |
| 38 | + |
| 39 | + |
| 40 | +if __name__ == "__main__": |
| 41 | + sdbus.set_default_bus(sdbus.sd_bus_open_system()) |
| 42 | + args = { |
| 43 | + # Set MyConnectionExample.ipv4.dns-search to "domain1.com,domain2.com": |
| 44 | + "connection_id": "MyConnectionExample", |
| 45 | + "connection_setting": ("ipv4", "dns-search"), |
| 46 | + # "as" is the so-called DBus signature, it means "array of strings": |
| 47 | + "value": ("as", ["domain1.com", "domain2.com"]), |
| 48 | + } |
| 49 | + asyncio.run(update_connection_async(args)) |
0 commit comments