1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#!/usr/bin/env python
# SPDX-License-Identifier: GPL-2.0-or-later
#
# Copyright (C) 2014 Red Hat, Inc.
#
#
# This example updates a connection's IPv4 method with the Update() method
# using the libnm GObject-based convenience APIs.
#
# Configuration settings are described at
# https://networkmanager.dev/docs/api/latest/ref-settings.html
#
import gi
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM
import sys, socket
if __name__ == "__main__":
# parse and validate arguments
if len(sys.argv) < 3:
print("Usage: %s <uuid> <auto|static> [address prefix gateway]" % sys.argv[0])
sys.exit(1)
method = sys.argv[2]
if (method == "static" or method == "manual") and len(sys.argv) < 5:
print(
"Usage: %s %s static address prefix [gateway]" % (sys.argv[0], sys.argv[1])
)
sys.exit(1)
uuid = sys.argv[1]
# Convert method to NM method
if method == "static":
method = "manual"
main_loop = GLib.MainLoop()
# create Client object
client = NM.Client.new(None)
try:
conn = next(c for c in client.get_connections() if c.get_uuid() == uuid)
except StopIteration:
sys.exit("not found connection with uuid=%s" % uuid)
# add IPv4 setting if it doesn't yet exist
s_ip4 = conn.get_setting_ip4_config()
if not s_ip4:
s_ip4 = NM.SettingIP4Config.new()
conn.add_setting(s_ip4)
# set the method and change properties
s_ip4.set_property(NM.SETTING_IP_CONFIG_METHOD, method)
if method == "auto":
# remove addresses and gateway
s_ip4.clear_addresses()
s_ip4.props.gateway = None
elif method == "manual":
# Add the static IP address, prefix, and (optional) gateway
addr = NM.IPAddress.new(socket.AF_INET, sys.argv[3], int(sys.argv[4]))
s_ip4.add_address(addr)
if len(sys.argv) == 6:
s_ip4.props.gateway = sys.argv[5]
try:
conn.commit_changes(True, None)
print("The connection profile has been updated.")
except Exception as e:
sys.stderr.write("Error: %s\n" % e)
|