Skip to content

Commit 9c2d811

Browse files
authored
Merge pull request #11 from bernhardkaindl/add-eth-conn-updates
add-eth-connection.py: Update like add-wifi-psk-connection
2 parents f0c940f + b14b7ee commit 9c2d811

File tree

2 files changed

+144
-24
lines changed

2 files changed

+144
-24
lines changed
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
#!/usr/bin/env python
2+
# SPDX-License-Identifier: LGPL-2.1-or-later
3+
#
4+
# Example to create a new Ethernet network connection profile:
5+
#
6+
# examples/block/add-eth-connection-async.py --help
7+
# usage: add-eth-connection-async.py [-h] [-c CONN_ID] [-u UUID] [-4 IP4]
8+
# [-i INTERFACE_NAME] [-g GW] [-a] [--save]
9+
#
10+
# Optional arguments have example values:
11+
#
12+
# optional arguments:
13+
# -h, --help show this help message and exit
14+
# -c CONN_ID Connection Id
15+
# -u UUID Connection UUID
16+
# -i INTERFACE_NAME ethX device
17+
# -4 IP4 IP4/prefix
18+
# -g GW gw/metric
19+
# -a autoconnect
20+
# --save Save
21+
#
22+
# Connection Profile settings are described at:
23+
# https://networkmanager.dev/docs/api/latest/ref-settings.html
24+
25+
import asyncio
26+
import sdbus
27+
import functools
28+
import logging
29+
import pprint
30+
import sys
31+
from uuid import uuid4
32+
from argparse import ArgumentParser, Namespace
33+
from sdbus_async.networkmanager import NetworkManagerSettings
34+
from sdbus_async.networkmanager import NetworkManagerConnectionProperties
35+
36+
37+
async def add_ethernet_connection_async(args: Namespace) -> str:
38+
"""Add a (by default) temporary (not yet saved) network connection profile
39+
:param Namespace args: autoconnect, conn_id, psk, save, ssid, uuid
40+
:return: dbus connection path of the created connection profile
41+
"""
42+
info = logging.getLogger().info
43+
44+
# If we add many connections using the same id, things get messy. Check:
45+
if await NetworkManagerSettings().get_connections_by_id(args.conn_id):
46+
info(f'Connections using ID "{args.conn_id}" exist, remove them:')
47+
info(f'Run: nmcli connection delete "{args.conn_id}"')
48+
return ""
49+
50+
ipaddr, prefix = args.ip4.split("/")
51+
properties: NetworkManagerConnectionProperties = {
52+
"connection": {
53+
"id": ("s", args.conn_id),
54+
"uuid": ("s", str(args.uuid)),
55+
"type": ("s", "802-3-ethernet"),
56+
"autoconnect": ("b", args.auto),
57+
},
58+
"ipv4": {
59+
"method": ("s", "manual"),
60+
"address-data": (
61+
"aa{sv}",
62+
[
63+
{
64+
"address": ("s", ipaddr),
65+
"prefix": ("u", int(prefix)),
66+
},
67+
],
68+
),
69+
},
70+
"ipv6": {"method": ("s", "disabled")},
71+
}
72+
if args.interface_name:
73+
properties["connection"]["interface-name"] = ("s", args.interface_name)
74+
if len(sys.argv) == 1 or args.gw != "192.0.2.1/4000":
75+
default_gateway, route_metric = args.gw.split("/")
76+
properties["ipv4"]["gateway"] = ("s", default_gateway)
77+
properties["ipv4"]["route-metric"] = ("u", int(route_metric))
78+
79+
s = NetworkManagerSettings()
80+
addconnection = s.add_connection if args.save else s.add_connection_unsaved
81+
connection_settings_dbus_path = await addconnection(properties)
82+
created = "created and saved" if args.save else "created"
83+
84+
info(f"New unsaved connection profile {created}, show it with:")
85+
info(f'nmcli connection show "{args.conn_id}"|grep -v -e -- -e default')
86+
info("Settings used:")
87+
info(functools.partial(pprint.pformat, sort_dicts=False)(properties))
88+
return connection_settings_dbus_path
89+
90+
91+
if __name__ == "__main__":
92+
logging.basicConfig(format="%(message)s", level=logging.INFO)
93+
p = ArgumentParser(description="Optional arguments have example values:")
94+
conn_id = "MyConnectionExample"
95+
p.add_argument("-c", dest="conn_id", default=conn_id, help="Connection Id")
96+
p.add_argument("-u", dest="uuid", default=uuid4(), help="Connection UUID")
97+
p.add_argument("-i", dest="interface_name", default="", help="ethX device")
98+
p.add_argument("-4", dest="ip4", default="192.0.2.8/24", help="IP4/prefix")
99+
p.add_argument("-g", dest="gw", default="192.0.2.1/4000", help="gw/metric")
100+
p.add_argument("-a", dest="auto", action="store_true", help="autoconnect")
101+
p.add_argument("--save", dest="save", action="store_true", help="Save")
102+
args = p.parse_args()
103+
sdbus.set_default_bus(sdbus.sd_bus_open_system())
104+
if connection_dpath := asyncio.run(add_ethernet_connection_async(args)):
105+
print(f"Path of the new connection: {connection_dpath}")
106+
print(f"UUID of the new connection: {args.uuid}")
107+
else:
108+
print("Error: No new connection created.")

examples/block/add-eth-connection.py

100644100755
Lines changed: 36 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,16 @@
33
#
44
# Example to create a new Ethernet network connection profile:
55
#
6-
# add-eth-connection.py --help
7-
# usage: add-eth-connection.py [-h] [-c CONN_ID] [-i INTERFACE_NAME] [-4 IP4]
8-
# [-g GW] [-a] [--save]
6+
# examples/block/add-eth-connection.py --help
7+
# usage: add-eth-connection.py [-h] [-c CONN_ID] [-u UUID] [-i INTERFACE_NAME]
8+
# [-4 IP4] [-g GW] [-a] [--save]
99
#
1010
# Optional arguments have example values:
1111
#
1212
# optional arguments:
1313
# -h, --help show this help message and exit
1414
# -c CONN_ID Connection Id
15+
# -u UUID Connection UUID
1516
# -i INTERFACE_NAME ethX device
1617
# -4 IP4 IP4/prefix
1718
# -g GW gw/metric
@@ -23,28 +24,33 @@
2324

2425
import sdbus
2526
import functools
27+
import logging
2628
import pprint
2729
import sys
28-
import uuid
30+
from uuid import uuid4
2931
from argparse import ArgumentParser, Namespace
3032
from sdbus_block.networkmanager import NetworkManagerSettings
3133
from sdbus_block.networkmanager import NetworkManagerConnectionProperties
3234

3335

34-
def add_ethernet_connection_profile(args: Namespace) -> None:
35-
"""Add a temporary (not yet saved) network connection profile"""
36+
def add_ethernet_connection(args: Namespace) -> str:
37+
"""Add a (by default) temporary (not yet saved) network connection profile
38+
:param Namespace args: autoconnect, conn_id, psk, save, ssid, uuid
39+
:return: dbus connection path of the created connection profile
40+
"""
41+
info = logging.getLogger().info
3642

3743
# If we add many connections using the same id, things get messy. Check:
3844
if NetworkManagerSettings().get_connections_by_id(args.conn_id):
39-
print(f'Connections using ID "{args.conn_id}" exist, remove them:')
40-
print(f'Run: nmcli connection delete "{args.conn_id}"')
41-
return
45+
info(f'Connections using ID "{args.conn_id}" exist, remove them:')
46+
info(f'Run: nmcli connection delete "{args.conn_id}"')
47+
return ""
4248

4349
ipaddr, prefix = args.ip4.split("/")
44-
profile: NetworkManagerConnectionProperties = {
50+
properties: NetworkManagerConnectionProperties = {
4551
"connection": {
4652
"id": ("s", args.conn_id),
47-
"uuid": ("s", str(uuid.uuid4())),
53+
"uuid": ("s", str(args.uuid)),
4854
"type": ("s", "802-3-ethernet"),
4955
"autoconnect": ("b", args.auto),
5056
},
@@ -63,33 +69,39 @@ def add_ethernet_connection_profile(args: Namespace) -> None:
6369
"ipv6": {"method": ("s", "disabled")},
6470
}
6571
if args.interface_name:
66-
profile["connection"]["interface-name"] = ("s", args.interface_name)
72+
properties["connection"]["interface-name"] = ("s", args.interface_name)
6773
if len(sys.argv) == 1 or args.gw != "192.0.2.1/4000":
6874
default_gateway, route_metric = args.gw.split("/")
69-
profile["ipv4"]["gateway"] = ("s", default_gateway)
70-
profile["ipv4"]["route-metric"] = ("u", int(route_metric))
75+
properties["ipv4"]["gateway"] = ("s", default_gateway)
76+
properties["ipv4"]["route-metric"] = ("u", int(route_metric))
7177

72-
if args.save:
73-
NetworkManagerSettings().add_connection(profile)
74-
print("New connection profile created and saved, show it with:")
75-
else:
76-
NetworkManagerSettings().add_connection_unsaved(profile)
77-
print("New unsaved connection profile created, show it with:")
78+
s = NetworkManagerSettings()
79+
addconnection = s.add_connection if args.save else s.add_connection_unsaved
80+
connection_settings_dbus_path = addconnection(properties)
81+
created = "created and saved" if args.save else "created"
7882

79-
print(f'nmcli connection show "{args.conn_id}"|grep -v -e -- -e default')
80-
print("Settings used:")
81-
functools.partial(pprint.pprint, sort_dicts=False)(profile)
83+
info(f"New unsaved connection profile {created}, show it with:")
84+
info(f'nmcli connection show "{args.conn_id}"|grep -v -e -- -e default')
85+
info("Settings used:")
86+
info(functools.partial(pprint.pformat, sort_dicts=False)(properties))
87+
return connection_settings_dbus_path
8288

8389

8490
if __name__ == "__main__":
91+
logging.basicConfig(format="%(message)s", level=logging.INFO)
8592
p = ArgumentParser(description="Optional arguments have example values:")
8693
conn_id = "MyConnectionExample"
8794
p.add_argument("-c", dest="conn_id", default=conn_id, help="Connection Id")
95+
p.add_argument("-u", dest="uuid", default=uuid4(), help="Connection UUID")
8896
p.add_argument("-i", dest="interface_name", default="", help="ethX device")
8997
p.add_argument("-4", dest="ip4", default="192.0.2.8/24", help="IP4/prefix")
9098
p.add_argument("-g", dest="gw", default="192.0.2.1/4000", help="gw/metric")
9199
p.add_argument("-a", dest="auto", action="store_true", help="autoconnect")
92100
p.add_argument("--save", dest="save", action="store_true", help="Save")
93101
args = p.parse_args()
94102
sdbus.set_default_bus(sdbus.sd_bus_open_system())
95-
add_ethernet_connection_profile(args)
103+
if connection_dpath := add_ethernet_connection(args):
104+
print(f"Path of the new connection: {connection_dpath}")
105+
print(f"UUID of the new connection: {args.uuid}")
106+
else:
107+
print("Error: No new connection created.")

0 commit comments

Comments
 (0)