diff options
Diffstat (limited to 'examples/python')
38 files changed, 933 insertions, 648 deletions
diff --git a/examples/python/dbus/add-connection-compat.py b/examples/python/dbus/add-connection-compat.py index 6c389f1b37..6acec734bc 100755 --- a/examples/python/dbus/add-connection-compat.py +++ b/examples/python/dbus/add-connection-compat.py @@ -20,34 +20,40 @@ import socket, struct, dbus, uuid def ip_to_int(ip_string): return struct.unpack("=I", socket.inet_aton(ip_string))[0] + def int_to_ip(ip_int): return socket.inet_ntoa(struct.pack("=I", ip_int)) -s_wired = dbus.Dictionary({'duplex': 'full'}) -s_con = dbus.Dictionary({ - 'type': '802-3-ethernet', - 'uuid': str(uuid.uuid4()), - 'id': 'MyConnectionExample'}) -addr1 = dbus.Array([ip_to_int("10.1.2.3"), dbus.UInt32(8), ip_to_int("10.1.2.1")], signature=dbus.Signature('u')) -s_ip4 = dbus.Dictionary({ - 'addresses': dbus.Array([addr1], signature=dbus.Signature('au')), - 'method': 'manual'}) +s_wired = dbus.Dictionary({"duplex": "full"}) +s_con = dbus.Dictionary( + {"type": "802-3-ethernet", "uuid": str(uuid.uuid4()), "id": "MyConnectionExample"} +) + +addr1 = dbus.Array( + [ip_to_int("10.1.2.3"), dbus.UInt32(8), ip_to_int("10.1.2.1")], + signature=dbus.Signature("u"), +) +s_ip4 = dbus.Dictionary( + { + "addresses": dbus.Array([addr1], signature=dbus.Signature("au")), + "method": "manual", + } +) -s_ip6 = dbus.Dictionary({'method': 'ignore'}) +s_ip6 = dbus.Dictionary({"method": "ignore"}) -con = dbus.Dictionary({ - '802-3-ethernet': s_wired, - 'connection': s_con, - 'ipv4': s_ip4, - 'ipv6': s_ip6}) +con = dbus.Dictionary( + {"802-3-ethernet": s_wired, "connection": s_con, "ipv4": s_ip4, "ipv6": s_ip6} +) -print("Creating connection:", s_con['id'], "-", s_con['uuid']) +print("Creating connection:", s_con["id"], "-", s_con["uuid"]) bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" +) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") settings.AddConnection(con) - diff --git a/examples/python/dbus/add-connection.py b/examples/python/dbus/add-connection.py index fec9343033..ee2deb2633 100755 --- a/examples/python/dbus/add-connection.py +++ b/examples/python/dbus/add-connection.py @@ -17,34 +17,33 @@ import dbus, uuid -s_wired = dbus.Dictionary({'duplex': 'full'}) -s_con = dbus.Dictionary({ - 'type': '802-3-ethernet', - 'uuid': str(uuid.uuid4()), - 'id': 'MyConnectionExample'}) +s_wired = dbus.Dictionary({"duplex": "full"}) +s_con = dbus.Dictionary( + {"type": "802-3-ethernet", "uuid": str(uuid.uuid4()), "id": "MyConnectionExample"} +) -addr1 = dbus.Dictionary({ - 'address': '10.1.2.3', - 'prefix': dbus.UInt32(8)}) -s_ip4 = dbus.Dictionary({ - 'address-data': dbus.Array([addr1], signature=dbus.Signature('a{sv}')), - 'gateway': '10.1.2.1', - 'method': 'manual'}) +addr1 = dbus.Dictionary({"address": "10.1.2.3", "prefix": dbus.UInt32(8)}) +s_ip4 = dbus.Dictionary( + { + "address-data": dbus.Array([addr1], signature=dbus.Signature("a{sv}")), + "gateway": "10.1.2.1", + "method": "manual", + } +) -s_ip6 = dbus.Dictionary({'method': 'ignore'}) +s_ip6 = dbus.Dictionary({"method": "ignore"}) -con = dbus.Dictionary({ - '802-3-ethernet': s_wired, - 'connection': s_con, - 'ipv4': s_ip4, - 'ipv6': s_ip6}) +con = dbus.Dictionary( + {"802-3-ethernet": s_wired, "connection": s_con, "ipv4": s_ip4, "ipv6": s_ip6} +) -print("Creating connection:", s_con['id'], "-", s_con['uuid']) +print("Creating connection:", s_con["id"], "-", s_con["uuid"]) bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" +) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") settings.AddConnection(con) - diff --git a/examples/python/dbus/add-wifi-eap-connection.py b/examples/python/dbus/add-wifi-eap-connection.py index 26111138aa..0386084da1 100755 --- a/examples/python/dbus/add-wifi-eap-connection.py +++ b/examples/python/dbus/add-wifi-eap-connection.py @@ -6,45 +6,57 @@ import dbus, uuid -def path_to_value(path): - return dbus.ByteArray("file://".encode("utf-8") + path.encode("utf-8") + "\0".encode("utf-8")) - -s_con = dbus.Dictionary({ - 'type': '802-11-wireless', - 'uuid': str(uuid.uuid4()), - 'id': 'My Wifi'}) - -s_wifi = dbus.Dictionary({ - 'ssid': dbus.ByteArray("homewifi".encode("utf-8")), - 'security': '802-11-wireless-security'}) - -s_wsec = dbus.Dictionary({'key-mgmt': 'wpa-eap'}) -s_8021x = dbus.Dictionary({ - 'eap': ['tls'], - 'identity': 'Bill Smith', - 'client-cert': path_to_value("/some/place/client.pem"), - 'ca-cert': path_to_value("/some/place/ca-cert.pem"), - 'private-key': path_to_value("/some/place/privkey.pem"), - 'private-key-password': "12345testing"}) - -s_ip4 = dbus.Dictionary({'method': 'auto'}) -s_ip6 = dbus.Dictionary({'method': 'ignore'}) - -con = dbus.Dictionary({ - 'connection': s_con, - '802-11-wireless': s_wifi, - '802-11-wireless-security': s_wsec, - '802-1x': s_8021x, - 'ipv4': s_ip4, - 'ipv6': s_ip6 - }) +def path_to_value(path): + return dbus.ByteArray( + "file://".encode("utf-8") + path.encode("utf-8") + "\0".encode("utf-8") + ) + + +s_con = dbus.Dictionary( + {"type": "802-11-wireless", "uuid": str(uuid.uuid4()), "id": "My Wifi"} +) + +s_wifi = dbus.Dictionary( + { + "ssid": dbus.ByteArray("homewifi".encode("utf-8")), + "security": "802-11-wireless-security", + } +) + +s_wsec = dbus.Dictionary({"key-mgmt": "wpa-eap"}) + +s_8021x = dbus.Dictionary( + { + "eap": ["tls"], + "identity": "Bill Smith", + "client-cert": path_to_value("/some/place/client.pem"), + "ca-cert": path_to_value("/some/place/ca-cert.pem"), + "private-key": path_to_value("/some/place/privkey.pem"), + "private-key-password": "12345testing", + } +) + +s_ip4 = dbus.Dictionary({"method": "auto"}) +s_ip6 = dbus.Dictionary({"method": "ignore"}) + +con = dbus.Dictionary( + { + "connection": s_con, + "802-11-wireless": s_wifi, + "802-11-wireless-security": s_wsec, + "802-1x": s_8021x, + "ipv4": s_ip4, + "ipv6": s_ip6, + } +) bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" +) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") settings.AddConnection(con) - diff --git a/examples/python/dbus/add-wifi-psk-connection.py b/examples/python/dbus/add-wifi-psk-connection.py index 8f2294f2fe..3e4f9da56f 100755 --- a/examples/python/dbus/add-wifi-psk-connection.py +++ b/examples/python/dbus/add-wifi-psk-connection.py @@ -6,38 +6,37 @@ import dbus, uuid -s_con = dbus.Dictionary({ - 'type': '802-11-wireless', - 'uuid': str(uuid.uuid4()), - 'id': 'My-WPA-PSK'}) - -s_wifi = dbus.Dictionary({ - 'ssid': dbus.ByteArray("best-wifi".encode("utf-8")), - 'mode': 'infrastructure', -}) - -s_wsec = dbus.Dictionary({ - 'key-mgmt': 'wpa-psk', - 'auth-alg': 'open', - 'psk': 'super-secret-password', -}) - -s_ip4 = dbus.Dictionary({'method': 'auto'}) -s_ip6 = dbus.Dictionary({'method': 'ignore'}) - -con = dbus.Dictionary({ - 'connection': s_con, - '802-11-wireless': s_wifi, - '802-11-wireless-security': s_wsec, - 'ipv4': s_ip4, - 'ipv6': s_ip6 - }) +s_con = dbus.Dictionary( + {"type": "802-11-wireless", "uuid": str(uuid.uuid4()), "id": "My-WPA-PSK"} +) + +s_wifi = dbus.Dictionary( + {"ssid": dbus.ByteArray("best-wifi".encode("utf-8")), "mode": "infrastructure",} +) + +s_wsec = dbus.Dictionary( + {"key-mgmt": "wpa-psk", "auth-alg": "open", "psk": "super-secret-password",} +) + +s_ip4 = dbus.Dictionary({"method": "auto"}) +s_ip6 = dbus.Dictionary({"method": "ignore"}) + +con = dbus.Dictionary( + { + "connection": s_con, + "802-11-wireless": s_wifi, + "802-11-wireless-security": s_wsec, + "ipv4": s_ip4, + "ipv6": s_ip6, + } +) bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" +) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") settings.AddConnection(con) - diff --git a/examples/python/dbus/checkpoint.py b/examples/python/dbus/checkpoint.py index 1ea1b1a7fc..54b450daf3 100755 --- a/examples/python/dbus/checkpoint.py +++ b/examples/python/dbus/checkpoint.py @@ -12,14 +12,18 @@ import dbus, sys # Get a proxy for the base NetworkManager object bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager") allDevs = manager.GetDevices() + def Usage(): print "Usage: %s <ROLLBACK-INTERVAL> [INTERFACE]..." % sys.argv[0] sys.exit(1) + def GetDevicePath(ifname): for dev in allDevs: dev_proxy = bus.get_object("org.freedesktop.NetworkManager", dev) @@ -29,6 +33,7 @@ def GetDevicePath(ifname): return dev return + if len(sys.argv) < 2: Usage() @@ -46,12 +51,11 @@ for arg in sys.argv[2:]: else: devList.append(path) -checkpoint = manager.CheckpointCreate(devList, - interval, - 1); # DESTROY_ALL +checkpoint = manager.CheckpointCreate(devList, interval, 1) +# DESTROY_ALL -choice = raw_input('Do you want to rollback [y/n]? ').lower() -if choice == 'y': +choice = raw_input("Do you want to rollback [y/n]? ").lower() +if choice == "y": print "Rollback checkpoint" results = manager.CheckpointRollback(checkpoint) for d in results: diff --git a/examples/python/dbus/create-bond.py b/examples/python/dbus/create-bond.py index 1ce988c34b..458c9c0618 100755 --- a/examples/python/dbus/create-bond.py +++ b/examples/python/dbus/create-bond.py @@ -17,51 +17,59 @@ from gi.repository import GObject DBusGMainLoop(set_as_default=True) + def add_connection(con): bus = dbus.SystemBus() - proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" + ) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") return settings.AddConnection(con) + def create_bond(bond_name): - bond_opts = dbus.Dictionary({'mode': '4'}) - s_bond = dbus.Dictionary({'options': bond_opts}) - s_con = dbus.Dictionary({ - 'type': 'bond', - 'uuid': str(uuid.uuid4()), - 'id': bond_name, - 'interface-name': bond_name, - 'autoconnect': False, - 'autoconnect-slaves': 1}) - s_ip4 = dbus.Dictionary({'method': 'auto'}) - s_ip6 = dbus.Dictionary({'method': 'ignore'}) - - con = dbus.Dictionary({ - 'bond': s_bond, - 'connection': s_con, - 'ipv4': s_ip4, - 'ipv6': s_ip6}) + bond_opts = dbus.Dictionary({"mode": "4"}) + s_bond = dbus.Dictionary({"options": bond_opts}) + s_con = dbus.Dictionary( + { + "type": "bond", + "uuid": str(uuid.uuid4()), + "id": bond_name, + "interface-name": bond_name, + "autoconnect": False, + "autoconnect-slaves": 1, + } + ) + s_ip4 = dbus.Dictionary({"method": "auto"}) + s_ip6 = dbus.Dictionary({"method": "ignore"}) + + con = dbus.Dictionary( + {"bond": s_bond, "connection": s_con, "ipv4": s_ip4, "ipv6": s_ip6} + ) print("Creating bond connection: %s" % bond_name) return add_connection(con) + def create_slave(device, master): - slave_name = 'bond-' + master + '-slave-' + device - s_wired = dbus.Dictionary({'duplex': 'full'}) - s_con = dbus.Dictionary({ - 'type': '802-3-ethernet', - 'uuid': str(uuid.uuid4()), - 'id': slave_name, - 'interface-name': device, - 'autoconnect': False, - 'master': master, - 'slave-type': 'bond'}) - - con = dbus.Dictionary({ - '802-3-ethernet': s_wired, - 'connection': s_con}) + slave_name = "bond-" + master + "-slave-" + device + s_wired = dbus.Dictionary({"duplex": "full"}) + s_con = dbus.Dictionary( + { + "type": "802-3-ethernet", + "uuid": str(uuid.uuid4()), + "id": slave_name, + "interface-name": device, + "autoconnect": False, + "master": master, + "slave-type": "bond", + } + ) + + con = dbus.Dictionary({"802-3-ethernet": s_wired, "connection": s_con}) print("Creating slave connection: %s" % slave_name) add_connection(con) + def usage(): print("Usage: %s <bond_name> <ifname1> ..." % sys.argv[0]) sys.exit(0) @@ -78,22 +86,27 @@ for ifname in sys.argv[2:]: # Activate the bond bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager") ac = manager.ActivateConnection(bond_path, "/", "/") print("Activating bond: %s (%s)" % (bond_name, ac)) # Monitor the active bond connection loop = GObject.MainLoop() + + def properties_changed(props): - if 'State' in props: - if props['State'] == 2: + if "State" in props: + if props["State"] == 2: print("Successfully connected") loop.quit() - if props['State'] == 3 or props['State'] == 4: + if props["State"] == 3 or props["State"] == 4: print("Bond activation failed") loop.quit() + obj = bus.get_object("org.freedesktop.NetworkManager", ac) iface = dbus.Interface(obj, "org.freedesktop.NetworkManager.Connection.Active") iface.connect_to_signal("PropertiesChanged", properties_changed) diff --git a/examples/python/dbus/disconnect-device.py b/examples/python/dbus/disconnect-device.py index 2387daf672..1b257025c5 100755 --- a/examples/python/dbus/disconnect-device.py +++ b/examples/python/dbus/disconnect-device.py @@ -16,7 +16,9 @@ if len(sys.argv) != 2: bus = dbus.SystemBus() # Get a proxy for the base NetworkManager object -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager") dpath = None @@ -45,4 +47,3 @@ if state <= 3: # Tell NM to disconnect it dev_iface.Disconnect() - diff --git a/examples/python/dbus/get-active-connection-uuids.py b/examples/python/dbus/get-active-connection-uuids.py index dd168c0aab..e138ce60a3 100755 --- a/examples/python/dbus/get-active-connection-uuids.py +++ b/examples/python/dbus/get-active-connection-uuids.py @@ -13,11 +13,15 @@ import dbus bus = dbus.SystemBus() # Get a proxy for the base NetworkManager object -m_proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +m_proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(m_proxy, "org.freedesktop.NetworkManager") mgr_props = dbus.Interface(m_proxy, "org.freedesktop.DBus.Properties") -s_proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") +s_proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" +) settings = dbus.Interface(s_proxy, "org.freedesktop.NetworkManager.Settings") # Find the device the user wants to disconnect @@ -31,12 +35,18 @@ for a in active: uuid = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Uuid") # Grab the connection object path so we can get all the connection's settings - connection_path = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection") + connection_path = a_props.Get( + "org.freedesktop.NetworkManager.Connection.Active", "Connection" + ) c_proxy = bus.get_object("org.freedesktop.NetworkManager", connection_path) - connection = dbus.Interface(c_proxy, "org.freedesktop.NetworkManager.Settings.Connection") + connection = dbus.Interface( + c_proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) settings = connection.GetSettings() - print("%s (%s) - %s" % (settings['connection']['id'], uuid, settings['connection']['type'])) + print( + "%s (%s) - %s" + % (settings["connection"]["id"], uuid, settings["connection"]["type"]) + ) if len(active) == 0: print("No active connections") - diff --git a/examples/python/dbus/is-wwan-default.py b/examples/python/dbus/is-wwan-default.py index d6e2b12e03..38dc1735c6 100755 --- a/examples/python/dbus/is-wwan-default.py +++ b/examples/python/dbus/is-wwan-default.py @@ -30,8 +30,9 @@ proxy = bus.get_object(NM_SERVICE_NAME, "/org/freedesktop/NetworkManager") manager = dbus.Interface(proxy, NM_MANAGER_IFACE) props = dbus.Interface(proxy, DBUS_PROPS_IFACE) + def found_connection_type(ctype): - if ctype == '': + if ctype == "": print("No active connection") elif ctype in ["gsm", "cdma", "bluetooth"]: print("WWAN is default") @@ -39,6 +40,7 @@ def found_connection_type(ctype): print("WWAN is not default") sys.exit(0) + # Shortcut #1, for NM 1.0 try: ctype = props.Get(NM_MANAGER_IFACE, "PrimaryConnectionType") @@ -50,7 +52,7 @@ except KeyError: try: primary = props.Get(NM_MANAGER_IFACE, "PrimaryConnection") if not primary: - found_connection_type('') + found_connection_type("") primary_proxy = bus.get_object(NM_SERVICE_NAME, primary) primary_props = dbus.Interface(primary_proxy, DBUS_PROPS_IFACE) ctype = primary_props.Get(NM_ACTIVE_CONNECTION_INTERFACE, "Type") @@ -83,4 +85,3 @@ if default_is_wwan: print("WWAN is default") else: print("WWAN is not default") - diff --git a/examples/python/dbus/list-connections.py b/examples/python/dbus/list-connections.py index 43a9c4e04f..2e096b632c 100755 --- a/examples/python/dbus/list-connections.py +++ b/examples/python/dbus/list-connections.py @@ -12,6 +12,7 @@ import dbus bus = dbus.SystemBus() + def merge_secrets(proxy, config, setting_name): try: # returns a dict of dicts mapping name::setting, where setting is a dict @@ -25,6 +26,7 @@ def merge_secrets(proxy, config, setting_name): except Exception as e: pass + def dict_to_string(d, indent): # Try to trivially translate a dictionary's elements into nice string # formatting. @@ -48,6 +50,7 @@ def dict_to_string(d, indent): dstr += "%s%s: %s\n" % (indent, key, str_val) return dstr + def connection_to_string(config): # dump a connection configuration to a the console for setting_name in config: @@ -66,29 +69,31 @@ def print_connections(): # List each connection's name, UUID, and type for path in connection_paths: con_proxy = bus.get_object(service_name, path) - settings_connection = dbus.Interface(con_proxy, "org.freedesktop.NetworkManager.Settings.Connection") + settings_connection = dbus.Interface( + con_proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) config = settings_connection.GetSettings() # Now get secrets too; we grab the secrets for each type of connection # (since there isn't a "get all secrets" call because most of the time # you only need 'wifi' secrets or '802.1x' secrets, not everything) and # merge that into the configuration data - merge_secrets(settings_connection, config, '802-11-wireless') - merge_secrets(settings_connection, config, '802-11-wireless-security') - merge_secrets(settings_connection, config, '802-1x') - merge_secrets(settings_connection, config, 'gsm') - merge_secrets(settings_connection, config, 'cdma') - merge_secrets(settings_connection, config, 'ppp') + merge_secrets(settings_connection, config, "802-11-wireless") + merge_secrets(settings_connection, config, "802-11-wireless-security") + merge_secrets(settings_connection, config, "802-1x") + merge_secrets(settings_connection, config, "gsm") + merge_secrets(settings_connection, config, "cdma") + merge_secrets(settings_connection, config, "ppp") # Get the details of the 'connection' setting - s_con = config['connection'] - print(" name: %s" % s_con['id']) - print(" uuid: %s" % s_con['uuid']) - print(" type: %s" % s_con['type']) + s_con = config["connection"] + print(" name: %s" % s_con["id"]) + print(" uuid: %s" % s_con["uuid"]) + print(" type: %s" % s_con["type"]) print(" ------------------------------------------") connection_to_string(config) print("") -print_connections() +print_connections() diff --git a/examples/python/dbus/list-devices.py b/examples/python/dbus/list-devices.py index aebc902bbe..882841e6a0 100755 --- a/examples/python/dbus/list-devices.py +++ b/examples/python/dbus/list-devices.py @@ -9,44 +9,49 @@ import dbus # This example lists basic information about network interfaces known to NM # For the types see include/NetworkManager.h -devtypes = { 1: "Ethernet", - 2: "Wi-Fi", - 5: "Bluetooth", - 6: "OLPC", - 7: "WiMAX", - 8: "Modem", - 9: "InfiniBand", - 10: "Bond", - 11: "VLAN", - 12: "ADSL", - 13: "Bridge", - 14: "Generic", - 15: "Team", - 16: "TUN", - 17: "IPTunnel", - 18: "MACVLAN", - 19: "VXLAN", - 20: "Veth" - } +devtypes = { + 1: "Ethernet", + 2: "Wi-Fi", + 5: "Bluetooth", + 6: "OLPC", + 7: "WiMAX", + 8: "Modem", + 9: "InfiniBand", + 10: "Bond", + 11: "VLAN", + 12: "ADSL", + 13: "Bridge", + 14: "Generic", + 15: "Team", + 16: "TUN", + 17: "IPTunnel", + 18: "MACVLAN", + 19: "VXLAN", + 20: "Veth", +} -states = { 0: "Unknown", - 10: "Unmanaged", - 20: "Unavailable", - 30: "Disconnected", - 40: "Prepare", - 50: "Config", - 60: "Need Auth", - 70: "IP Config", - 80: "IP Check", - 90: "Secondaries", - 100: "Activated", - 110: "Deactivating", - 120: "Failed" } +states = { + 0: "Unknown", + 10: "Unmanaged", + 20: "Unavailable", + 30: "Disconnected", + 40: "Prepare", + 50: "Config", + 60: "Need Auth", + 70: "IP Config", + 80: "IP Check", + 90: "Secondaries", + 100: "Activated", + 110: "Deactivating", + 120: "Failed", +} bus = dbus.SystemBus() # Get a proxy for the base NetworkManager object -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager") # Get all devices known to NM and print their properties @@ -57,18 +62,17 @@ for d in devices: props = prop_iface.GetAll("org.freedesktop.NetworkManager.Device") print("============================") - print("Interface: %s" % props['Interface']) + print("Interface: %s" % props["Interface"]) try: - devtype = devtypes[props['DeviceType']] + devtype = devtypes[props["DeviceType"]] except KeyError: devtype = "Unknown" print("Type: %s" % devtype) - print("Driver: %s" % props['Driver']) + print("Driver: %s" % props["Driver"]) try: - state = states[props['State']] + state = states[props["State"]] except KeyError: state = "Unknown" print("State: %s" % state) - diff --git a/examples/python/dbus/nm-state.py b/examples/python/dbus/nm-state.py index 38d10ae60d..c380bd093c 100755 --- a/examples/python/dbus/nm-state.py +++ b/examples/python/dbus/nm-state.py @@ -7,38 +7,46 @@ import dbus # Device states from include/NetworkManager.h -device_states = { 0: "Unknown", - 10: "Unmanaged", - 20: "Unavailable", - 30: "Disconnected", - 40: "Prepare", - 50: "Config", - 60: "Need Auth", - 70: "IP Config", - 80: "IP Check", - 90: "Secondaries", - 100: "Activated", - 110: "Deactivating", - 120: "Failed" } +device_states = { + 0: "Unknown", + 10: "Unmanaged", + 20: "Unavailable", + 30: "Disconnected", + 40: "Prepare", + 50: "Config", + 60: "Need Auth", + 70: "IP Config", + 80: "IP Check", + 90: "Secondaries", + 100: "Activated", + 110: "Deactivating", + 120: "Failed", +} -connectivity_states = { 0: "Unknown", - 1: "Activating", - 2: "Activated", - 3: "Deactivating", - 4: "Deactivated" } +connectivity_states = { + 0: "Unknown", + 1: "Activating", + 2: "Activated", + 3: "Deactivating", + 4: "Deactivated", +} -nm_state = { 0: "Unknown", - 10: "Asleep", - 20: "Disconnected", - 30: "Disconnecting", - 40: "Connecting", - 50: "Connected-Local", - 60: "Connected-Site", - 70: "Connected-Global" } +nm_state = { + 0: "Unknown", + 10: "Asleep", + 20: "Disconnected", + 30: "Disconnecting", + 40: "Connecting", + 50: "Connected-Local", + 60: "Connected-Site", + 70: "Connected-Global", +} bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager") # Get overall NM connection state @@ -55,7 +63,7 @@ for d in devices: name = prop_iface.Get("org.freedesktop.NetworkManager.Device", "Interface") # and print them out - if state == 100 : # activated + if state == 100: # activated print("Device %s is activated" % name) else: print("Device %s is not activated (state=%s)" % (name, device_states[state])) @@ -72,10 +80,14 @@ for a in active: # Connections in NM are a collection of settings that describe everything # needed to connect to a specific network. Lets get those details so we # can find the user-readable name of the connection. - con_path = prop_iface.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection") + con_path = prop_iface.Get( + "org.freedesktop.NetworkManager.Connection.Active", "Connection" + ) service_proxy = bus.get_object("org.freedesktop.NetworkManager", con_path) - con_iface = dbus.Interface(service_proxy, "org.freedesktop.NetworkManager.Settings.Connection") + con_iface = dbus.Interface( + service_proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) con_details = con_iface.GetSettings() - con_name = con_details['connection']['id'] + con_name = con_details["connection"]["id"] print("Connection '%s' is %s" % (con_name, connectivity_states[state].lower())) diff --git a/examples/python/dbus/show-bssids.py b/examples/python/dbus/show-bssids.py index b4217a5546..1e7181fece 100755 --- a/examples/python/dbus/show-bssids.py +++ b/examples/python/dbus/show-bssids.py @@ -14,7 +14,9 @@ import dbus bus = dbus.SystemBus() # Get a proxy for the base NetworkManager object -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" +) manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager") all_aps = [] @@ -35,20 +37,26 @@ for d in devices: # Get device's type; we only want wifi devices iface = prop_iface.Get("org.freedesktop.NetworkManager.Device", "Interface") dtype = prop_iface.Get("org.freedesktop.NetworkManager.Device", "DeviceType") - if dtype == 2: # WiFi + if dtype == 2: # WiFi # Get a proxy for the wifi interface - wifi_iface = dbus.Interface(dev_proxy, "org.freedesktop.NetworkManager.Device.Wireless") + wifi_iface = dbus.Interface( + dev_proxy, "org.freedesktop.NetworkManager.Device.Wireless" + ) wifi_prop_iface = dbus.Interface(dev_proxy, "org.freedesktop.DBus.Properties") # Get the associated AP's object path - connected_path = wifi_prop_iface.Get("org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint") + connected_path = wifi_prop_iface.Get( + "org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint" + ) # Get all APs the card can see aps = wifi_iface.GetAccessPoints() for path in aps: ap_proxy = bus.get_object("org.freedesktop.NetworkManager", path) ap_prop_iface = dbus.Interface(ap_proxy, "org.freedesktop.DBus.Properties") - bssid = ap_prop_iface.Get("org.freedesktop.NetworkManager.AccessPoint", "HwAddress") + bssid = ap_prop_iface.Get( + "org.freedesktop.NetworkManager.AccessPoint", "HwAddress" + ) # Cache the BSSID if not bssid in all_aps: @@ -62,4 +70,3 @@ for d in devices: print("\nFound APs:") for bssid in all_aps: print(bssid) - diff --git a/examples/python/dbus/update-ip4-method.py b/examples/python/dbus/update-ip4-method.py index 2c12c2bb5b..98927903a0 100755 --- a/examples/python/dbus/update-ip4-method.py +++ b/examples/python/dbus/update-ip4-method.py @@ -30,42 +30,49 @@ if method == "static": method = "manual" bus = dbus.SystemBus() -proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") +proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" +) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") for c_path in settings.ListConnections(): c_proxy = bus.get_object("org.freedesktop.NetworkManager", c_path) - c_obj = dbus.Interface(c_proxy, "org.freedesktop.NetworkManager.Settings.Connection") + c_obj = dbus.Interface( + c_proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) c_settings = c_obj.GetSettings() # Look for the requested connection UUID - if c_settings['connection']['uuid'] != sys.argv[1]: + if c_settings["connection"]["uuid"] != sys.argv[1]: continue # add IPv4 setting if it doesn't yet exist - if 'ipv4' not in c_settings: - c_settings['ipv4'] = {} + if "ipv4" not in c_settings: + c_settings["ipv4"] = {} # clear existing address info - if c_settings['ipv4'].has_key('addresses'): - del c_settings['ipv4']['addresses'] - if c_settings['ipv4'].has_key('address-data'): - del c_settings['ipv4']['address-data'] - if c_settings['ipv4'].has_key('gateway'): - del c_settings['ipv4']['gateway'] + if c_settings["ipv4"].has_key("addresses"): + del c_settings["ipv4"]["addresses"] + if c_settings["ipv4"].has_key("address-data"): + del c_settings["ipv4"]["address-data"] + if c_settings["ipv4"].has_key("gateway"): + del c_settings["ipv4"]["gateway"] # set the method and change properties - c_settings['ipv4']['method'] = method + c_settings["ipv4"]["method"] = method if method == "manual": # Add the static IP address, prefix, and (optional) gateway - addr = dbus.Dictionary({'address': sys.argv[3], 'prefix': dbus.UInt32(int(sys.argv[4]))}) - c_settings['ipv4']['address-data'] = dbus.Array([addr], signature=dbus.Signature('a{sv}')) + addr = dbus.Dictionary( + {"address": sys.argv[3], "prefix": dbus.UInt32(int(sys.argv[4]))} + ) + c_settings["ipv4"]["address-data"] = dbus.Array( + [addr], signature=dbus.Signature("a{sv}") + ) if len(sys.argv) == 6: - c_settings['ipv4']['gateway'] = sys.argv[5] + c_settings["ipv4"]["gateway"] = sys.argv[5] # Save all the updated settings back to NetworkManager c_obj.Update(c_settings) break sys.exit(0) - diff --git a/examples/python/dbus/update-secrets.py b/examples/python/dbus/update-secrets.py index a0b53b7c76..d5c20b2d4b 100755 --- a/examples/python/dbus/update-secrets.py +++ b/examples/python/dbus/update-secrets.py @@ -18,6 +18,7 @@ import sys bus = dbus.SystemBus() + def change_secrets_in_one_setting(proxy, config, setting_name): # Add new secret values to the connection config try: @@ -29,50 +30,62 @@ def change_secrets_in_one_setting(proxy, config, setting_name): # Ask user for new secrets and put them into our connection config for setting in secrets: for key in secrets[setting]: - new_secret = raw_input ("Enter new secret for '%s' in '%s': " % (key, setting)) + new_secret = raw_input( + "Enter new secret for '%s' in '%s': " % (key, setting) + ) config[setting_name][key] = new_secret except Exception as e: - #code = str(e).split(':')[0] - #print("Exception:" + str(e)) + # code = str(e).split(':')[0] + # print("Exception:" + str(e)) pass + def change_secrets(con_path, config): # Get existing secrets; we grab the secrets for each type of connection # (since there isn't a "get all secrets" call because most of the time # you only need 'wifi' secrets or '802.1x' secrets, not everything) and # set new values into the connection settings (config) con_proxy = bus.get_object("org.freedesktop.NetworkManager", con_path) - connection_secrets = dbus.Interface(con_proxy, "org.freedesktop.NetworkManager.Settings.Connection") - change_secrets_in_one_setting(connection_secrets, config, '802-11-wireless') - change_secrets_in_one_setting(connection_secrets, config, '802-11-wireless-security') - change_secrets_in_one_setting(connection_secrets, config, '802-1x') - change_secrets_in_one_setting(connection_secrets, config, 'gsm') - change_secrets_in_one_setting(connection_secrets, config, 'cdma') - change_secrets_in_one_setting(connection_secrets, config, 'ppp') + connection_secrets = dbus.Interface( + con_proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) + change_secrets_in_one_setting(connection_secrets, config, "802-11-wireless") + change_secrets_in_one_setting( + connection_secrets, config, "802-11-wireless-security" + ) + change_secrets_in_one_setting(connection_secrets, config, "802-1x") + change_secrets_in_one_setting(connection_secrets, config, "gsm") + change_secrets_in_one_setting(connection_secrets, config, "cdma") + change_secrets_in_one_setting(connection_secrets, config, "ppp") + def find_connection(name): # Ask the settings service for the list of connections it provides global con_path - proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings") + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" + ) settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings") connection_paths = settings.ListConnections() # Get the settings and look for connection's name for path in connection_paths: con_proxy = bus.get_object("org.freedesktop.NetworkManager", path) - connection = dbus.Interface(con_proxy, "org.freedesktop.NetworkManager.Settings.Connection") + connection = dbus.Interface( + con_proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) try: config = connection.GetSettings() except Exception as e: pass # Find connection by the id - s_con = config['connection'] - if name == s_con['id']: + s_con = config["connection"] + if name == s_con["id"]: con_path = path return config # Find connection by the uuid - if name == s_con['uuid']: + if name == s_con["uuid"]: con_path = path return config @@ -96,8 +109,9 @@ if con: # Change the connection with Update() proxy = bus.get_object("org.freedesktop.NetworkManager", con_path) - settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings.Connection") + settings = dbus.Interface( + proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) settings.Update(con) else: sys.exit("No connection '%s' found" % sys.argv[1]) - diff --git a/examples/python/dbus/vpn.py b/examples/python/dbus/vpn.py index 14fa2f1d2e..ed38137280 100755 --- a/examples/python/dbus/vpn.py +++ b/examples/python/dbus/vpn.py @@ -8,11 +8,11 @@ # Run this script without any arguments to list the available connection uuids. # The uuid of the connection to activate -CONNECTION_UUID="ac6dc9b2-85ef-4311-83d8-add5d7db3f59" +CONNECTION_UUID = "ac6dc9b2-85ef-4311-83d8-add5d7db3f59" # UID to use. Note that NM only allows the owner of the connection to activate it. -#UID=1000 -UID=0 +# UID=1000 +UID = 0 import sys import os @@ -22,20 +22,27 @@ import gobject DBusGMainLoop(set_as_default=True) + def get_connections(): bus = dbus.SystemBus() - proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager/Settings') - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings') + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings" + ) + iface = dbus.Interface( + proxy, dbus_interface="org.freedesktop.NetworkManager.Settings" + ) return iface.ListConnections() def get_connection_by_uuid(uuid): bus = dbus.SystemBus() for c in get_connections(): - proxy = bus.get_object('org.freedesktop.NetworkManager', c) - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings.Connection') + proxy = bus.get_object("org.freedesktop.NetworkManager", c) + iface = dbus.Interface( + proxy, dbus_interface="org.freedesktop.NetworkManager.Settings.Connection" + ) settings = iface.GetSettings() - if settings['connection']['uuid'] == uuid: + if settings["connection"]["uuid"] == uuid: return c return None @@ -44,29 +51,39 @@ def get_connection_by_uuid(uuid): def list_uuids(): bus = dbus.SystemBus() for c in get_connections(): - proxy = bus.get_object('org.freedesktop.NetworkManager', c) - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings.Connection') + proxy = bus.get_object("org.freedesktop.NetworkManager", c) + iface = dbus.Interface( + proxy, dbus_interface="org.freedesktop.NetworkManager.Settings.Connection" + ) settings = iface.GetSettings() - conn = settings['connection'] - print("%s - %s (%s)" % (conn['uuid'], conn['id'], conn['type'])) + conn = settings["connection"] + print("%s - %s (%s)" % (conn["uuid"], conn["id"], conn["type"])) def get_active_connection_path(uuid): bus = dbus.SystemBus() - proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') - active_connections = iface.Get('org.freedesktop.NetworkManager', 'ActiveConnections') + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" + ) + iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.DBus.Properties") + active_connections = iface.Get( + "org.freedesktop.NetworkManager", "ActiveConnections" + ) for a in active_connections: - proxy = bus.get_object('org.freedesktop.NetworkManager', a) - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') - path = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection') - - proxy = bus.get_object('org.freedesktop.NetworkManager', path) - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings.Connection') + proxy = bus.get_object("org.freedesktop.NetworkManager", a) + iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.DBus.Properties") + path = iface.Get( + "org.freedesktop.NetworkManager.Connection.Active", "Connection" + ) + + proxy = bus.get_object("org.freedesktop.NetworkManager", path) + iface = dbus.Interface( + proxy, dbus_interface="org.freedesktop.NetworkManager.Settings.Connection" + ) settings = iface.GetSettings() - if settings['connection']['uuid'] == uuid: + if settings["connection"]["uuid"] == uuid: return a return None @@ -74,19 +91,21 @@ def get_active_connection_path(uuid): def get_wifi_device_path(): bus = dbus.SystemBus() - proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager') + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" + ) + iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.NetworkManager") devices = iface.GetDevices() for d in devices: - proxy = bus.get_object('org.freedesktop.NetworkManager', d) - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') - devtype = iface.Get('org.freedesktop.NetworkManager.Device', 'DeviceType') + proxy = bus.get_object("org.freedesktop.NetworkManager", d) + iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.DBus.Properties") + devtype = iface.Get("org.freedesktop.NetworkManager.Device", "DeviceType") if devtype == 2: return d return None -def activate_connection(connection_path, device_path): +def activate_connection(connection_path, device_path): def reply_handler(opath): print("Success: device activating") sys.exit(0) @@ -96,14 +115,18 @@ def activate_connection(connection_path, device_path): sys.exit(1) bus = dbus.SystemBus() - proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') - iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager') - iface.ActivateConnection('org.freedesktop.NetworkManager', - connection_path, - device_path, - "/", - reply_handler=reply_handler, - error_handler=error_handler) + proxy = bus.get_object( + "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" + ) + iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.NetworkManager") + iface.ActivateConnection( + "org.freedesktop.NetworkManager", + connection_path, + device_path, + "/", + reply_handler=reply_handler, + error_handler=error_handler, + ) # Change the UID first if required @@ -135,4 +158,3 @@ print("Activating connection...") activate_connection(connection_path, device_path) loop = gobject.MainLoop() loop.run() - diff --git a/examples/python/dbus/wifi-active-ap.py b/examples/python/dbus/wifi-active-ap.py index b81c06a933..33fae0b219 100755 --- a/examples/python/dbus/wifi-active-ap.py +++ b/examples/python/dbus/wifi-active-ap.py @@ -31,7 +31,9 @@ devpath = nm.GetDeviceByIpIface(iface) # Get a proxy to the wifi device and get the active access point's object path proxy = bus.get_object(service_name, devpath) props = dbus.Interface(proxy, "org.freedesktop.DBus.Properties") -active_ap_path = props.Get("org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint") +active_ap_path = props.Get( + "org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint" +) if active_ap_path == "/": print("%s is not currently associated" % sys.argv[1]) sys.exit(0) @@ -50,4 +52,3 @@ for c in raw_ssid: print("%s is associated to '%s' (%s)" % (sys.argv[1], ssid, bssid)) sys.exit(0) - diff --git a/examples/python/dbus/wifi-hotspot.py b/examples/python/dbus/wifi-hotspot.py index d4f17d074b..a3c573a643 100755 --- a/examples/python/dbus/wifi-hotspot.py +++ b/examples/python/dbus/wifi-hotspot.py @@ -13,38 +13,42 @@ import dbus, sys, time -our_uuid = '2b0d0f1d-b79d-43af-bde1-71744625642e' - -s_con = dbus.Dictionary({ - 'type': '802-11-wireless', - 'uuid': our_uuid, - 'id': 'Test Hotspot'}) - -s_wifi = dbus.Dictionary({ - 'ssid': dbus.ByteArray("My Hotspot".encode("utf-8")), - 'mode': "ap", - 'band': "bg", - 'channel': dbus.UInt32(1)}) - -s_wsec = dbus.Dictionary({ - 'key-mgmt': 'wpa-psk', - 'psk': 'great password'}) - -s_ip4 = dbus.Dictionary({'method': 'shared'}) -s_ip6 = dbus.Dictionary({'method': 'ignore'}) - -con = dbus.Dictionary({ - 'connection': s_con, - '802-11-wireless': s_wifi, - '802-11-wireless-security': s_wsec, - 'ipv4': s_ip4, - 'ipv6': s_ip6 - }) +our_uuid = "2b0d0f1d-b79d-43af-bde1-71744625642e" + +s_con = dbus.Dictionary( + {"type": "802-11-wireless", "uuid": our_uuid, "id": "Test Hotspot"} +) + +s_wifi = dbus.Dictionary( + { + "ssid": dbus.ByteArray("My Hotspot".encode("utf-8")), + "mode": "ap", + "band": "bg", + "channel": dbus.UInt32(1), + } +) + +s_wsec = dbus.Dictionary({"key-mgmt": "wpa-psk", "psk": "great password"}) + +s_ip4 = dbus.Dictionary({"method": "shared"}) +s_ip6 = dbus.Dictionary({"method": "ignore"}) + +con = dbus.Dictionary( + { + "connection": s_con, + "802-11-wireless": s_wifi, + "802-11-wireless-security": s_wsec, + "ipv4": s_ip4, + "ipv6": s_ip6, + } +) + def usage(): print("Usage: %s <ifname> [up|down]" % sys.argv[0]) sys.exit(0) + bus = dbus.SystemBus() service_name = "org.freedesktop.NetworkManager" proxy = bus.get_object(service_name, "/org/freedesktop/NetworkManager/Settings") @@ -62,9 +66,11 @@ devpath = nm.GetDeviceByIpIface(iface) connection_path = None for path in settings.ListConnections(): proxy = bus.get_object(service_name, path) - settings_connection = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings.Connection") + settings_connection = dbus.Interface( + proxy, "org.freedesktop.NetworkManager.Settings.Connection" + ) config = settings_connection.GetSettings() - if config['connection']['uuid'] == our_uuid: + if config["connection"]["uuid"] == our_uuid: connection_path = path break @@ -84,7 +90,9 @@ if operation == "up": # Wait for the hotspot to start up start = time.time() while time.time() < start + 10: - state = active_props.Get("org.freedesktop.NetworkManager.Connection.Active", "State") + state = active_props.Get( + "org.freedesktop.NetworkManager.Connection.Active", "State" + ) if state == 2: # NM_ACTIVE_CONNECTION_STATE_ACTIVATED print("Access point started") sys.exit(0) @@ -96,4 +104,3 @@ else: usage() sys.exit(0) - diff --git a/examples/python/gi/add_connection.py b/examples/python/gi/add_connection.py index 9cf9e348f1..ac537eada4 100755 --- a/examples/python/gi/add_connection.py +++ b/examples/python/gi/add_connection.py @@ -14,15 +14,18 @@ # import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM import sys, uuid main_loop = None + def print_values(setting, key, value, flags, data): print(" %s.%s: %s" % (setting.get_name(), key, value)) + # create an Ethernet connection and return it def create_profile(name): profile = NM.SimpleConnection.new() @@ -49,6 +52,7 @@ def create_profile(name): return profile + # callback function def added_cb(client, result, data): try: @@ -58,16 +62,17 @@ def added_cb(client, result, data): sys.stderr.write("Error: %s\n" % e) main_loop.quit() + if __name__ == "__main__": # parse arguments persistent = False if len(sys.argv) != 2 and len(sys.argv) != 3: - sys.exit('Usage: %s <connection name> [persistent]' % sys.argv[0]) + sys.exit("Usage: %s <connection name> [persistent]" % sys.argv[0]) if len(sys.argv) == 3: if sys.argv[2] in "persistent" and sys.argv[2][:1] == "p": persistent = True else: - sys.exit('Usage: %s <connection name> [persistent]' % sys.argv[0]) + sys.exit("Usage: %s <connection name> [persistent]" % sys.argv[0]) profile_name = sys.argv[1] main_loop = GLib.MainLoop() @@ -82,4 +87,3 @@ if __name__ == "__main__": client.add_connection_async(con, persistent, None, added_cb, None) main_loop.run() - diff --git a/examples/python/gi/checkpoint.py b/examples/python/gi/checkpoint.py index a695a64613..6dfd3d4488 100755 --- a/examples/python/gi/checkpoint.py +++ b/examples/python/gi/checkpoint.py @@ -7,32 +7,52 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM ############################################################################### + def usage(): print("Usage: %s [COMMAND [ARG]...]" % sys.argv[0]) print("") print(" COMMANDS: [show]") - print(" create TIMEOUT [--destroy-all|--delete-new-connections|--disconnect-new-devices|--allow-overlapping|DEV]...") + print( + " create TIMEOUT [--destroy-all|--delete-new-connections|--disconnect-new-devices|--allow-overlapping|DEV]..." + ) print(" destroy PATH|NUMBER") print(" rollback PATH|NUMBER") print(" adjust-rollback-timeout PATH|NUMBER TIMEOUT") print("") sys.exit(1) -def show(c, ts = None): + +def show(c, ts=None): cr = c.get_created() rt = c.get_rollback_timeout() print("%s:" % c.get_path()) - print(" created: %u%s" % (cr, "" if ts is None else (" (%s sec ago)" % ((ts - cr) / 1000.0)))) + print( + " created: %u%s" + % (cr, "" if ts is None else (" (%s sec ago)" % ((ts - cr) / 1000.0))) + ) if rt == 0: print(" timeout: infinity") else: - print(" timeout: %u seconds%s" % (rt, "" if ts is None else (" (circa %s sec left)" % ((cr + (rt * 1000) - ts) / 1000.0)))) - print(" devices: %s" % (' '.join(sorted(map(lambda x: x.get_iface(), c.get_devices()))))) + print( + " timeout: %u seconds%s" + % ( + rt, + "" + if ts is None + else (" (circa %s sec left)" % ((cr + (rt * 1000) - ts) / 1000.0)), + ) + ) + print( + " devices: %s" + % (" ".join(sorted(map(lambda x: x.get_iface(), c.get_devices())))) + ) + def find_checkpoint(client, path): for c in client.get_checkpoints(): @@ -40,6 +60,7 @@ def find_checkpoint(client, path): return c return None + def validate_path(path, client): try: num = int(path) @@ -47,8 +68,8 @@ def validate_path(path, client): except Exception as e: pass - if not path or path[0] != '/': - sys.exit('Invalid checkpoint path \"%s\"' % (path)) + if not path or path[0] != "/": + sys.exit('Invalid checkpoint path "%s"' % (path)) if client is not None: checkpoint = find_checkpoint(client, path) @@ -57,6 +78,7 @@ def validate_path(path, client): return path + def do_create(client): flags = NM.CheckpointCreateFlags.NONE if len(sys.argv) < 3: @@ -65,13 +87,13 @@ def do_create(client): timeout = int(sys.argv[2]) devices = [] for arg in sys.argv[3:]: - if arg == '--destroy-all': + if arg == "--destroy-all": flags |= NM.CheckpointCreateFlags.DESTROY_ALL - elif arg == '--delete-new-connections': + elif arg == "--delete-new-connections": flags |= NM.CheckpointCreateFlags.DELETE_NEW_CONNECTIONS - elif arg == '--disconnect-new-devices': + elif arg == "--disconnect-new-devices": flags |= NM.CheckpointCreateFlags.DISCONNECT_NEW_DEVICES - elif arg == '--allow-overlapping': + elif arg == "--allow-overlapping": flags |= NM.CheckpointCreateFlags.ALLOW_OVERLAPPING else: d = client.get_device_by_iface(arg) @@ -89,6 +111,7 @@ def do_create(client): client.checkpoint_create(devices, timeout, flags, None, create_cb, None) + def do_destroy(client): if len(sys.argv) < 3: sys.exit("Missing checkpoint path") @@ -105,6 +128,7 @@ def do_destroy(client): client.checkpoint_destroy(path, None, destroy_cb, None) + def do_rollback(client): if len(sys.argv) < 3: sys.exit("Missing checkpoint path") @@ -127,6 +151,7 @@ def do_rollback(client): client.checkpoint_rollback(path, None, rollback_cb, None) + def do_adjust_rollback_timeout(client): if len(sys.argv) < 3: sys.exit("Missing checkpoint path") @@ -147,27 +172,31 @@ def do_adjust_rollback_timeout(client): sys.stderr.write("Failed: %s\n" % e.message) main_loop.quit() - client.checkpoint_adjust_rollback_timeout(path, add_timeout, None, adjust_rollback_timeout_cb, None) + client.checkpoint_adjust_rollback_timeout( + path, add_timeout, None, adjust_rollback_timeout_cb, None + ) + def do_show(client): ts = NM.utils_get_timestamp_msec() for c in client.get_checkpoints(): show(c, ts) -if __name__ == '__main__': + +if __name__ == "__main__": nm_client = NM.Client.new(None) main_loop = GLib.MainLoop() - if len(sys.argv) < 2 or sys.argv[1] == 'show': + if len(sys.argv) < 2 or sys.argv[1] == "show": do_show(nm_client) sys.exit(0) - elif sys.argv[1] == 'create': + elif sys.argv[1] == "create": do_create(nm_client) - elif sys.argv[1] == 'destroy': + elif sys.argv[1] == "destroy": do_destroy(nm_client) - elif sys.argv[1] == 'rollback': + elif sys.argv[1] == "rollback": do_rollback(nm_client) - elif sys.argv[1] == 'adjust-rollback-timeout': + elif sys.argv[1] == "adjust-rollback-timeout": do_adjust_rollback_timeout(nm_client) else: usage() diff --git a/examples/python/gi/deactivate-all.py b/examples/python/gi/deactivate-all.py index 7e528d0b3e..cc181dd97c 100755 --- a/examples/python/gi/deactivate-all.py +++ b/examples/python/gi/deactivate-all.py @@ -16,24 +16,25 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM # supported connection types connection_types = { - NM.SETTING_VPN_SETTING_NAME, - NM.SETTING_WIRELESS_SETTING_NAME, - NM.SETTING_WIRED_SETTING_NAME, - NM.SETTING_BOND_SETTING_NAME, - NM.SETTING_BRIDGE_SETTING_NAME, - NM.SETTING_TEAM_SETTING_NAME, - NM.SETTING_INFINIBAND_SETTING_NAME, - NM.SETTING_PPPOE_SETTING_NAME, - NM.SETTING_ADSL_SETTING_NAME, - NM.SETTING_BLUETOOTH_SETTING_NAME, - NM.SETTING_WIMAX_SETTING_NAME, - NM.SETTING_OLPC_MESH_SETTING_NAME, - NM.SETTING_GENERIC_SETTING_NAME, + NM.SETTING_VPN_SETTING_NAME, + NM.SETTING_WIRELESS_SETTING_NAME, + NM.SETTING_WIRED_SETTING_NAME, + NM.SETTING_BOND_SETTING_NAME, + NM.SETTING_BRIDGE_SETTING_NAME, + NM.SETTING_TEAM_SETTING_NAME, + NM.SETTING_INFINIBAND_SETTING_NAME, + NM.SETTING_PPPOE_SETTING_NAME, + NM.SETTING_ADSL_SETTING_NAME, + NM.SETTING_BLUETOOTH_SETTING_NAME, + NM.SETTING_WIMAX_SETTING_NAME, + NM.SETTING_OLPC_MESH_SETTING_NAME, + NM.SETTING_GENERIC_SETTING_NAME, } @@ -45,9 +46,14 @@ if __name__ == "__main__": if len(sys.argv) == 2: ctype = sys.argv[1] if ctype not in connection_types: - sys.exit('Usage: %s [<type>]\nAllowed types: %s' % (sys.argv[0], allowed_types)) + sys.exit( + "Usage: %s [<type>]\nAllowed types: %s" + % (sys.argv[0], allowed_types) + ) else: - sys.exit('Usage: %s [<type>]\nAllowed types: %s' % (sys.argv[0], allowed_types)) + sys.exit( + "Usage: %s [<type>]\nAllowed types: %s" % (sys.argv[0], allowed_types) + ) # create Client object client = NM.Client.new(None) @@ -63,5 +69,4 @@ if __name__ == "__main__": client.deactivate_connection(ac, None) sys.stdout.write("\033[32m -> succeeded\033[0m\n") except Exception as e: - sys.stderr.write("\033[31m -> failed\033[0m (%s)\n" % e.message) - + sys.stderr.write("\033[31m -> failed\033[0m (%s)\n" % e.message) diff --git a/examples/python/gi/device-state-ip4config.py b/examples/python/gi/device-state-ip4config.py index 18848d07fc..038b8a725f 100755 --- a/examples/python/gi/device-state-ip4config.py +++ b/examples/python/gi/device-state-ip4config.py @@ -6,7 +6,8 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM # @@ -18,6 +19,7 @@ from gi.repository import GLib, NM main_loop = None + def do_notify(self, property): print("notify: %s" % property) ip4cfg = self.get_ip4_config() @@ -25,26 +27,26 @@ def do_notify(self, property): print("ip4-config: %s" % ip4cfg.get_path()) main_loop.quit() + def state_changed(obj, arg1, arg2, arg3): print("State changed: New: %d, Old: %d, Reason: %d" % (arg1, arg2, arg3)) # Device is connected if arg1 == 100: - obj.connect('notify::ip4-config', do_notify) + obj.connect("notify::ip4-config", do_notify) if __name__ == "__main__": if len(sys.argv) != 2: - sys.exit('Usage: %s <interface>' % sys.argv[0]) + sys.exit("Usage: %s <interface>" % sys.argv[0]) dev_iface = sys.argv[1] c = NM.Client.new(None) dev = c.get_device_by_iface(dev_iface) if dev is None: - sys.exit('Device \'%s\' not found' % dev_iface) + sys.exit("Device '%s' not found" % dev_iface) print("Device: %s - %s" % (dev_iface, dev.get_device_type().value_name)) print("---------------------------------------") - dev.connect('state-changed', state_changed) + dev.connect("state-changed", state_changed) main_loop = GLib.MainLoop() main_loop.run() - diff --git a/examples/python/gi/dns.py b/examples/python/gi/dns.py index da2a6a6c43..c4c5190152 100755 --- a/examples/python/gi/dns.py +++ b/examples/python/gi/dns.py @@ -5,24 +5,26 @@ # import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM # This example shows how to monitor the DNS configuration main_loop = None + def handle_config(config): print " ---- new configuration ----" for entry in config: - print " * servers: %s" % ', '.join(map(str, entry.get_nameservers())) + print " * servers: %s" % ", ".join(map(str, entry.get_nameservers())) domains = entry.get_domains() if domains and domains[0]: - print " domains: %s" % ', '.join(map(str, domains)) + print " domains: %s" % ", ".join(map(str, domains)) if entry.get_interface(): - print " interface: %s" % entry.get_interface() + print " interface: %s" % entry.get_interface() print " priority: %d" % entry.get_priority() @@ -31,9 +33,11 @@ def handle_config(config): print "" + def dns_config_changed(self, property): handle_config(self.get_dns_configuration()) + main_loop = None if __name__ == "__main__": diff --git a/examples/python/gi/firewall-zone.py b/examples/python/gi/firewall-zone.py index 6cbd8c2549..3de06f5255 100755 --- a/examples/python/gi/firewall-zone.py +++ b/examples/python/gi/firewall-zone.py @@ -6,7 +6,8 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM # @@ -26,13 +27,15 @@ from gi.repository import GLib, NM main_loop = None + def connection_saved(connection, error, data): - print ("Connection '%s' saved.") % (connection.get_id()) + print("Connection '%s' saved.") % (connection.get_id()) main_loop.quit() + if __name__ == "__main__": if len(sys.argv) != 2 and len(sys.argv) != 3: - sys.exit('Usage: %s <connection name or UUID> [new zone]' % sys.argv[0]) + sys.exit("Usage: %s <connection name or UUID> [new zone]" % sys.argv[0]) main_loop = GLib.MainLoop() client = NM.Client.new(None) diff --git a/examples/python/gi/get-active-connections.py b/examples/python/gi/get-active-connections.py index 6da8b61890..c2f261abe0 100755 --- a/examples/python/gi/get-active-connections.py +++ b/examples/python/gi/get-active-connections.py @@ -7,7 +7,8 @@ # This example lists currently active connections import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM if __name__ == "__main__": @@ -16,6 +17,4 @@ if __name__ == "__main__": for ac in acons: print("%s (%s) - %s" % (ac.get_id(), ac.get_uuid(), ac.get_connection_type())) if len(acons) == 0: - print("No active connections") - - + print("No active connections") diff --git a/examples/python/gi/get-devices.py b/examples/python/gi/get-devices.py index 88bcc8945b..057db5ace0 100755 --- a/examples/python/gi/get-devices.py +++ b/examples/python/gi/get-devices.py @@ -7,7 +7,8 @@ # This example lists all devices, both real and placeholder ones import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM if __name__ == "__main__": @@ -18,11 +19,18 @@ if __name__ == "__main__": print "------------" for d in devices: if d.is_real(): - print "%s (%s): %s" % (d.get_iface(), d.get_type_description(), d.get_state()) + print "%s (%s): %s" % ( + d.get_iface(), + d.get_type_description(), + d.get_state(), + ) print "\nUnrealized/placeholder devices" print "------------------------------" for d in devices: if not d.is_real(): - print "%s (%s): %s" % (d.get_iface(), d.get_type_description(), d.get_state()) - + print "%s (%s): %s" % ( + d.get_iface(), + d.get_type_description(), + d.get_state(), + ) diff --git a/examples/python/gi/get-interface-flags.py b/examples/python/gi/get-interface-flags.py index e1d1721a4f..2b4fa3b4ea 100755 --- a/examples/python/gi/get-interface-flags.py +++ b/examples/python/gi/get-interface-flags.py @@ -5,7 +5,8 @@ # import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM if __name__ == "__main__": @@ -13,7 +14,10 @@ if __name__ == "__main__": devices = client.get_devices() for d in devices: - print("{:<16} {:<16} {}".format(d.get_iface(), - "(" + d.get_type_description() + ")", - NM.utils_enum_to_str(NM.DeviceInterfaceFlags, - d.get_interface_flags()))) + print( + "{:<16} {:<16} {}".format( + d.get_iface(), + "(" + d.get_type_description() + ")", + NM.utils_enum_to_str(NM.DeviceInterfaceFlags, d.get_interface_flags()), + ) + ) diff --git a/examples/python/gi/get-lldp-neighbors.py b/examples/python/gi/get-lldp-neighbors.py index d1bed32c6b..b84a1c7389 100755 --- a/examples/python/gi/get-lldp-neighbors.py +++ b/examples/python/gi/get-lldp-neighbors.py @@ -6,7 +6,8 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM # This example shows how to get a list of LLDP neighbors for a given interface. @@ -15,24 +16,24 @@ main_loop = None if __name__ == "__main__": if len(sys.argv) != 2: - sys.exit('Usage: %s <interface>' % sys.argv[0]) + sys.exit("Usage: %s <interface>" % sys.argv[0]) dev_iface = sys.argv[1] c = NM.Client.new(None) dev = c.get_device_by_iface(dev_iface) if dev is None: - sys.exit('Device \'%s\' not found' % dev_iface) + sys.exit("Device '%s' not found" % dev_iface) neighbors = dev.get_lldp_neighbors() for neighbor in neighbors: - ret, chassis = neighbor.get_attr_string_value('chassis-id') - ret, port = neighbor.get_attr_string_value('port-id') + ret, chassis = neighbor.get_attr_string_value("chassis-id") + ret, port = neighbor.get_attr_string_value("port-id") print "Neighbor: %s - %s" % (chassis, port) for attr in neighbor.get_attr_names(): attr_type = neighbor.get_attr_type(attr) - if attr_type.equal(GLib.VariantType.new('s')): + if attr_type.equal(GLib.VariantType.new("s")): ret, value = neighbor.get_attr_string_value(attr) print " %-32s: %s" % (attr, value) - elif attr_type.equal(GLib.VariantType.new('u')): + elif attr_type.equal(GLib.VariantType.new("u")): ret, value = neighbor.get_attr_uint_value(attr) print " %-32s: %u" % (attr, value) diff --git a/examples/python/gi/get_ips.py b/examples/python/gi/get_ips.py index 75be2f8c5d..07d6f0cc39 100755 --- a/examples/python/gi/get_ips.py +++ b/examples/python/gi/get_ips.py @@ -6,7 +6,8 @@ import sys, socket import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM # @@ -14,11 +15,12 @@ from gi.repository import NM # from NMIP4Config and NMIP6Config (got out of NMDevice) # + def show_addresses(dev, family): - if (family == socket.AF_INET): - ip_cfg = dev.get_ip4_config() + if family == socket.AF_INET: + ip_cfg = dev.get_ip4_config() else: - ip_cfg = dev.get_ip6_config() + ip_cfg = dev.get_ip6_config() if ip_cfg is None: print("None") @@ -35,8 +37,9 @@ def show_addresses(dev, family): print("%s/%d") % (addr, prefix) + def show_gateway(dev, family): - if (family == socket.AF_INET): + if family == socket.AF_INET: ip_cfg = dev.get_ip4_config() else: ip_cfg = dev.get_ip6_config() @@ -45,16 +48,17 @@ def show_gateway(dev, family): gw = "None" else: gw = ip_cfg.get_gateway() - if gw == '': + if gw == "": gw = "None" print(gw) + def show_routes(dev, family): - if (family == socket.AF_INET): - ip_cfg = dev.get_ip4_config() + if family == socket.AF_INET: + ip_cfg = dev.get_ip4_config() else: - ip_cfg = dev.get_ip6_config() + ip_cfg = dev.get_ip6_config() if ip_cfg is None: print("None") @@ -75,31 +79,31 @@ def show_routes(dev, family): def show_dns(dev, family): - if (family == socket.AF_INET): - ip_cfg = dev.get_ip4_config() + if family == socket.AF_INET: + ip_cfg = dev.get_ip4_config() else: - ip_cfg = dev.get_ip6_config() + ip_cfg = dev.get_ip6_config() if ip_cfg is None: print("None") return - print ("Nameservers: %s") % (ip_cfg.get_nameservers()) - print ("Domains: %s") % (ip_cfg.get_domains()) - print ("Searches: %s") % (ip_cfg.get_searches()) - if (family == socket.AF_INET): - print ("WINS: %s") % (ip_cfg.get_wins_servers()) + print("Nameservers: %s") % (ip_cfg.get_nameservers()) + print("Domains: %s") % (ip_cfg.get_domains()) + print("Searches: %s") % (ip_cfg.get_searches()) + if family == socket.AF_INET: + print("WINS: %s") % (ip_cfg.get_wins_servers()) if __name__ == "__main__": if len(sys.argv) != 2: - sys.exit('Usage: %s <interface>' % sys.argv[0]) + sys.exit("Usage: %s <interface>" % sys.argv[0]) dev_iface = sys.argv[1] c = NM.Client.new(None) dev = c.get_device_by_iface(dev_iface) if dev is None: - sys.exit('Device \'%s\' not found' % dev_iface) + sys.exit("Device '%s' not found" % dev_iface) print("Device: %s - %s" % (dev_iface, dev.get_device_type().value_name)) print("---------------------------------------") @@ -142,4 +146,3 @@ if __name__ == "__main__": print("------------") show_dns(dev, socket.AF_INET6) print - diff --git a/examples/python/gi/list-connections.py b/examples/python/gi/list-connections.py index 7278fafd9b..ba4f50e2fa 100755 --- a/examples/python/gi/list-connections.py +++ b/examples/python/gi/list-connections.py @@ -5,14 +5,17 @@ # import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM # This example asks settings service for all configured connections. + def print_values(setting, key, value, flags, data): print(" %s.%s: %s" % (setting.get_name(), key, value)) + if __name__ == "__main__": # create Client object client = NM.Client.new(None) @@ -25,4 +28,3 @@ if __name__ == "__main__": print("=== %s : %s ===" % (c.get_id(), c.get_path())) c.for_each_setting_value(print_values, None) print("\n") - diff --git a/examples/python/gi/nm-add-connection2.py b/examples/python/gi/nm-add-connection2.py index c5ec3f3bbe..f487e0bbe4 100755 --- a/examples/python/gi/nm-add-connection2.py +++ b/examples/python/gi/nm-add-connection2.py @@ -7,40 +7,47 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM + def find_connections(nm_client, arg_type, arg_id): for c in nm_client.get_connections(): - if arg_type in [None, 'id'] and c.get_id() == arg_id: + if arg_type in [None, "id"] and c.get_id() == arg_id: yield c - if arg_type in [None, 'uuid'] and c.get_uuid() == arg_id: + if arg_type in [None, "uuid"] and c.get_uuid() == arg_id: yield c + def find_connection_first(nm_client, arg_type, arg_id): for f in find_connections(nm_client, arg_type, arg_id): return f + def con_to_str(con): s_con = con.get_setting_connection() return '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid()) + def usage(): arg0 = sys.argv[0] - arg0_spaced = ' ' * len(arg0) - print('Usage: %s [ --clone ( [id] <id> | [uuid] <uuid> ) ] \\' % (arg0)) - print(' %s [ --to-disk | --in-memory ] \\' % (arg0_spaced)) - print(' %s [ --block-autoconnect ] \\' % (arg0_spaced)) - print(' %s [ --id <new-id> ] \\' % (arg0_spaced)) - print(' %s [ --uuid <new-uuid> ] \\' % (arg0_spaced)) + arg0_spaced = " " * len(arg0) + print("Usage: %s [ --clone ( [id] <id> | [uuid] <uuid> ) ] \\" % (arg0)) + print(" %s [ --to-disk | --in-memory ] \\" % (arg0_spaced)) + print(" %s [ --block-autoconnect ] \\" % (arg0_spaced)) + print(" %s [ --id <new-id> ] \\" % (arg0_spaced)) + print(" %s [ --uuid <new-uuid> ] \\" % (arg0_spaced)) return 1 + def die(msg, print_usage=False): print(msg) if print_usage: usage() sys.exit(1) + def main(): main_loop = GLib.MainLoop() @@ -56,56 +63,62 @@ def main(): argv = list(sys.argv[1:]) while argv: - if argv[0] == '--clone': + if argv[0] == "--clone": match_type = None if len(argv) < 2: - die('missing argument for --clone option') - if argv[0] in ['id', 'uuid']: + die("missing argument for --clone option") + if argv[0] in ["id", "uuid"]: match_type = argv[0] if len(argv) < 3: die('missing argument for "--clone %s" option' % (match_type)) argv = argv[1:] if cons: - die('cannot specify --clone argument more than once') + die("cannot specify --clone argument more than once") cons.extend(find_connections(nm_client, match_type, argv[1])) if len(cons) == 0: - die('could not find connection for "--clone %s%s"' % ((match_type or ''), argv[1])) + die( + 'could not find connection for "--clone %s%s"' + % ((match_type or ""), argv[1]) + ) if len(cons) != 1: - die('could not find unique connection for "--clone %s%s"' % ((match_type or ''), argv[1])) + die( + 'could not find unique connection for "--clone %s%s"' + % ((match_type or ""), argv[1]) + ) argv = argv[2:] continue - if argv[0] in ['--block-autoconnect']: + if argv[0] in ["--block-autoconnect"]: arg_block_autoconnect = NM.SettingsAddConnection2Flags.BLOCK_AUTOCONNECT argv = argv[1:] continue - if argv[0] in ['--to-disk', '--in-memory']: - if argv[0] == '--to-disk': + if argv[0] in ["--to-disk", "--in-memory"]: + if argv[0] == "--to-disk": v = NM.SettingsAddConnection2Flags.TO_DISK - elif argv[0] == '--in-memory': + elif argv[0] == "--in-memory": v = NM.SettingsAddConnection2Flags.IN_MEMORY else: - assert(False) + assert False if arg_mode is not None: die('duplicate storage modes ("%s")' % (argv[0])) arg_mode = v argv = argv[1:] continue - if argv[0] in ['--id']: + if argv[0] in ["--id"]: if len(argv) < 2: - die('missing argument for --id option') + die("missing argument for --id option") arg_id = argv[1] argv = argv[2:] continue - if argv[0] in ['--uuid']: + if argv[0] in ["--uuid"]: if len(argv) < 2: - die('missing argument for --uuid option') + die("missing argument for --uuid option") arg_uuid = argv[1] argv = argv[2:] continue die('unknown argument "%s"' % (argv[0])) if len(cons) != 1: - die('missing --clone argument', True) + die("missing --clone argument", True) con = cons[0] @@ -117,31 +130,46 @@ def main(): s_con.set_property(NM.SETTING_CONNECTION_UUID, arg_uuid or NM.utils_uuid_generate()) result = {} + def _add_connection2_cb(cl, async_result, user_data): try: c, r = nm_client.add_connection2_finish(async_result) except Exception as e: - result['error'] = e + result["error"] = e else: - result['result'] = r - result['connection'] = c + result["result"] = r + result["connection"] = c main_loop.quit() - nm_client.add_connection2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL), - (arg_mode if arg_mode is not None else NM.SettingsAddConnection2Flags.TO_DISK) - | arg_block_autoconnect, - None, - False, - None, - _add_connection2_cb, - None) + nm_client.add_connection2( + con2.to_dbus(NM.ConnectionSerializationFlags.ALL), + (arg_mode if arg_mode is not None else NM.SettingsAddConnection2Flags.TO_DISK) + | arg_block_autoconnect, + None, + False, + None, + _add_connection2_cb, + None, + ) main_loop.run() - if 'error' in result: - die('update connection %s failed [%s]: %s' % (con_to_str(con2), ' '.join(sys.argv), result['error'])) + if "error" in result: + die( + "update connection %s failed [%s]: %s" + % (con_to_str(con2), " ".join(sys.argv), result["error"]) + ) + + print( + "update connection %s succeeded [%s]: %s, %s" + % ( + con_to_str(con2), + " ".join(sys.argv), + result["connection"].get_path(), + result["result"], + ) + ) - print('update connection %s succeeded [%s]: %s, %s' % (con_to_str(con2), ' '.join(sys.argv), result['connection'].get_path(), result['result'])) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/examples/python/gi/nm-connection-update-stable-id.py b/examples/python/gi/nm-connection-update-stable-id.py index 3629d07230..091a67d618 100755 --- a/examples/python/gi/nm-connection-update-stable-id.py +++ b/examples/python/gi/nm-connection-update-stable-id.py @@ -11,33 +11,37 @@ import sys import re import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM + def usage(): - print('Usage: %s [[id] <id>]' % (sys.argv[0])) - print(' %s [[uuid] <uuid>]' % (sys.argv[0])) + print("Usage: %s [[id] <id>]" % (sys.argv[0])) + print(" %s [[uuid] <uuid>]" % (sys.argv[0])) return 1 + def find_connection(nm_client, arg_type, arg_id): for c in nm_client.get_connections(): - if arg_type in [None, 'id'] and c.get_id() == arg_id: + if arg_type in [None, "id"] and c.get_id() == arg_id: return c - if arg_type in [None, 'uuid'] and c.get_uuid() == arg_id: + if arg_type in [None, "uuid"] and c.get_uuid() == arg_id: return c + def main(): if len(sys.argv) < 2 or len(sys.argv) > 3: return usage() if len(sys.argv) == 3: arg_type = sys.argv[1] arg_id = sys.argv[2] - if arg_type not in ['id', 'uuid']: + if arg_type not in ["id", "uuid"]: return usage() else: arg_type = None arg_id = sys.argv[1] - arg_log = '%s"%s"' % ((' with %s ' % (arg_type)) if arg_type else '', arg_id) + arg_log = '%s"%s"' % ((" with %s " % (arg_type)) if arg_type else "", arg_id) main_loop = GLib.MainLoop() @@ -45,57 +49,61 @@ def main(): con = find_connection(nm_client, arg_type, arg_id) if con is None: - print('could not find a connection %s' % (arg_log)) + print("could not find a connection %s" % (arg_log)) return 1 s_con = con.get_setting_connection() if s_con is None: - print('connection %s has no [connection] setting' % (arg_log)) + print("connection %s has no [connection] setting" % (arg_log)) return 1 arg_log = '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid()) stable_id = s_con.get_stable_id() if not stable_id: - print('connection %s has no stable-id set' % (arg_log)) + print("connection %s has no stable-id set" % (arg_log)) return 1 - re_match = re.search('\A(.*)-([0-9]+)\Z', stable_id) + re_match = re.search("\A(.*)-([0-9]+)\Z", stable_id) if not re_match: - stable_id = stable_id + '-1' + stable_id = stable_id + "-1" else: - stable_id = re_match.group(1) + '-' + str(int(re_match.group(2)) + 1) + stable_id = re_match.group(1) + "-" + str(int(re_match.group(2)) + 1) con2 = NM.SimpleConnection.new_clone(con) s_con = con2.get_setting_connection() s_con.set_property(NM.SETTING_CONNECTION_STABLE_ID, stable_id) result = {} + def _update2_cb(con, async_result, user_data): try: r = con.update2_finish(async_result) except Exception as e: - result['error'] = e + result["error"] = e else: - result['result'] = r + result["result"] = r main_loop.quit() - con.update2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL), - NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT, - None, - None, - _update2_cb, - None) + con.update2( + con2.to_dbus(NM.ConnectionSerializationFlags.ALL), + NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT, + None, + None, + _update2_cb, + None, + ) main_loop.run() - if 'error' in result: - print('update connection %s failed: %s' % (arg_log, result['error'])) + if "error" in result: + print("update connection %s failed: %s" % (arg_log, result["error"])) return 1 - print('update connection %s succeeded: %s' % (arg_log, result['result'])) + print("update connection %s succeeded: %s" % (arg_log, result["result"])) print('set stable-id to "%s"' % (stable_id)) return 0 -if __name__ == '__main__': + +if __name__ == "__main__": sys.exit(main()) diff --git a/examples/python/gi/nm-update2.py b/examples/python/gi/nm-update2.py index 23e277c78d..192768eeec 100755 --- a/examples/python/gi/nm-update2.py +++ b/examples/python/gi/nm-update2.py @@ -7,40 +7,50 @@ import sys import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM + def find_connections(nm_client, arg_type, arg_id): for c in nm_client.get_connections(): - if arg_type in [None, 'id'] and c.get_id() == arg_id: + if arg_type in [None, "id"] and c.get_id() == arg_id: yield c - if arg_type in [None, 'uuid'] and c.get_uuid() == arg_id: + if arg_type in [None, "uuid"] and c.get_uuid() == arg_id: yield c + def find_connection_first(nm_client, arg_type, arg_id): for f in find_connections(nm_client, arg_type, arg_id): return f + def con_to_str(con): s_con = con.get_setting_connection() return '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid()) + def usage(): arg0 = sys.argv[0] - arg0_spaced = ' ' * len(arg0) - print('Usage: %s [ [id] <id> | [uuid] <uuid> ] \\' % (arg0)) - print(' %s [ --to-disk | --in-memory | --in-memory-detached | --in-memory-only ] \\' % (arg0_spaced)) - print(' %s [ --block-autoconnect ] \\' % (arg0_spaced)) - print(' %s [ --volatile ] \\' % (arg0_spaced)) - print(' %s [ --no-reapply ] \\' % (arg0_spaced)) + arg0_spaced = " " * len(arg0) + print("Usage: %s [ [id] <id> | [uuid] <uuid> ] \\" % (arg0)) + print( + " %s [ --to-disk | --in-memory | --in-memory-detached | --in-memory-only ] \\" + % (arg0_spaced) + ) + print(" %s [ --block-autoconnect ] \\" % (arg0_spaced)) + print(" %s [ --volatile ] \\" % (arg0_spaced)) + print(" %s [ --no-reapply ] \\" % (arg0_spaced)) return 1 + def die(msg, print_usage=False): print(msg) if print_usage: usage() sys.exit(1) + def main(): main_loop = GLib.MainLoop() @@ -56,9 +66,9 @@ def main(): argv = list(sys.argv[1:]) while argv: - if argv[0] in ['id', 'uuid']: + if argv[0] in ["id", "uuid"]: if cons: - die('cannot specify multiple connections') + die("cannot specify multiple connections") if len(argv) < 2: die('missing argument for "%s" specifier' % (argv[0])) cons.extend(find_connections(nm_client, argv[0], argv[1])) @@ -68,31 +78,36 @@ def main(): die('could not find unique connection for "%s %s"' % (argv[0], argv[1])) argv = argv[2:] continue - if argv[0] in ['--block-autoconnect']: + if argv[0] in ["--block-autoconnect"]: arg_block_autoconnect = NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT argv = argv[1:] continue - if argv[0] in ['--volatile']: + if argv[0] in ["--volatile"]: arg_volatile = NM.SettingsUpdate2Flags.VOLATILE argv = argv[1:] continue - if argv[0] in ['--no-reapply']: + if argv[0] in ["--no-reapply"]: arg_no_reapply = NM.SettingsUpdate2Flags.NO_REAPPLY argv = argv[1:] continue - if argv[0] in ['--to-disk', '--in-memory', '--in-memory-detached', '--in-memory-only']: - if argv[0] == '--to-disk': + if argv[0] in [ + "--to-disk", + "--in-memory", + "--in-memory-detached", + "--in-memory-only", + ]: + if argv[0] == "--to-disk": v = NM.SettingsUpdate2Flags.TO_DISK - elif argv[0] == '--in-memory': + elif argv[0] == "--in-memory": v = NM.SettingsUpdate2Flags.IN_MEMORY - elif argv[0] == '--in-memory-detached': + elif argv[0] == "--in-memory-detached": v = NM.SettingsUpdate2Flags.IN_MEMORY_DETACHED - elif argv[0] == '--in-memory-only': + elif argv[0] == "--in-memory-only": v = NM.SettingsUpdate2Flags.IN_MEMORY_ONLY - elif argv[0] == '--keep': + elif argv[0] == "--keep": v = NM.SettingsUpdate2Flags.NONE else: - assert(False) + assert False if arg_mode is not None: die('duplicate storage modes ("%s")' % (argv[0])) arg_mode = v @@ -102,45 +117,55 @@ def main(): die('unknown argument "%s"' % (argv[0])) cons.extend(find_connections(nm_client, None, argv[0])) if len(cons) == 0: - die('could not find connection for "%s"' % (argv[0])) + die('could not find connection for "%s"' % (argv[0])) if len(cons) != 1: - die('could not find unique connection for "%s"' % (argv[0])) + die('could not find unique connection for "%s"' % (argv[0])) argv = argv[1:] continue if len(cons) != 1: - die('missing connection argument', True) + die("missing connection argument", True) con = cons[0] con2 = NM.SimpleConnection.new_clone(con) result = {} + def _update2_cb(con, async_result, user_data): try: r = con.update2_finish(async_result) except Exception as e: - result['error'] = e + result["error"] = e else: - result['result'] = r + result["result"] = r main_loop.quit() - con.update2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL), - (arg_mode if arg_mode is not None else NM.SettingsUpdate2Flags.NONE) - | arg_block_autoconnect - | arg_volatile - | arg_no_reapply, - None, - None, - _update2_cb, - None) + con.update2( + con2.to_dbus(NM.ConnectionSerializationFlags.ALL), + (arg_mode if arg_mode is not None else NM.SettingsUpdate2Flags.NONE) + | arg_block_autoconnect + | arg_volatile + | arg_no_reapply, + None, + None, + _update2_cb, + None, + ) main_loop.run() - if 'error' in result: - die('update connection %s failed [%s]: %s' % (con_to_str(con2), ' '.join(sys.argv), result['error'])) + if "error" in result: + die( + "update connection %s failed [%s]: %s" + % (con_to_str(con2), " ".join(sys.argv), result["error"]) + ) + + print( + "update connection %s succeeded [%s]: %s" + % (con_to_str(con2), " ".join(sys.argv), result["result"]) + ) - print('update connection %s succeeded [%s]: %s' % (con_to_str(con2), ' '.join(sys.argv), result['result'])) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/examples/python/gi/setting-user-data.py b/examples/python/gi/setting-user-data.py index fd86445b84..e21940743d 100755 --- a/examples/python/gi/setting-user-data.py +++ b/examples/python/gi/setting-user-data.py @@ -39,59 +39,60 @@ import sys import re import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM + def pr(v): import pprint + pprint.pprint(v, indent=4, depth=5, width=60) + def parse_args(): - args = { - 'set': False, - 'set-gobject': False, - 'filter': [], - 'data': [] - } + args = {"set": False, "set-gobject": False, "filter": [], "data": []} i = 1 while i < len(sys.argv): a = sys.argv[i] if i == 1: - if a in ['s', 'set']: - args['set'] = True + if a in ["s", "set"]: + args["set"] = True i += 1 continue - elif a in ['g', 'get']: - args['set'] = False + elif a in ["g", "get"]: + args["set"] = False i += 1 continue - if a in ['id', 'uuid']: - args['filter'].append((a, sys.argv[i+1])) + if a in ["id", "uuid"]: + args["filter"].append((a, sys.argv[i + 1])) i += 2 continue - if a in ['--set-gobject']: - args['set-gobject'] = True + if a in ["--set-gobject"]: + args["set-gobject"] = True i += 1 continue - if a == 'data': + if a == "data": i += 1 a = sys.argv[i] - if args['set']: - if a == '-d': - args['data'].append((sys.argv[i+1], None)) + if args["set"]: + if a == "-d": + args["data"].append((sys.argv[i + 1], None)) else: - args['data'].append((a, sys.argv[i+1])) + args["data"].append((a, sys.argv[i + 1])) i += 2 else: - args['data'].append(a) + args["data"].append(a) i += 1 return args + def connection_to_str(connection): - return '%s (%s)' % (connection.get_id(), connection.get_uuid()) + return "%s (%s)" % (connection.get_id(), connection.get_uuid()) + def connections_filter(connections, filter_data): connections = list(sorted(connections, key=connection_to_str)) @@ -102,20 +103,21 @@ def connections_filter(connections, filter_data): # them multiple times. l = [] for f in filter_data: - if f[0] == 'id': + if f[0] == "id": for c in connections: if f[1] == c.get_id(): l.append(c) else: - assert(f[0] == 'uuid') + assert f[0] == "uuid" for c in connections: if f[1] == c.get_uuid(): l.append(c) return l -def print_user_data(connection, data_allow_regex, data, prefix=''): + +def print_user_data(connection, data_allow_regex, data, prefix=""): s_u = connection.get_setting(NM.SettingUser) - n = 'none' + n = "none" keys_len = 0 keys = [] if s_u is not None: @@ -123,17 +125,17 @@ def print_user_data(connection, data_allow_regex, data, prefix=''): keys_len = len(all_keys) if data: for d in data: - if data_allow_regex and len(d) > 0 and d[0] == '~': + if data_allow_regex and len(d) > 0 and d[0] == "~": r = re.compile(d[1:]) keys.extend([k for k in all_keys if r.match(k)]) else: - keys.append (d) + keys.append(d) else: keys.extend(all_keys) - n = '%s' % (keys_len) + n = "%s" % (keys_len) - print('%s%s [%s]' % (prefix, connection_to_str(connection), n)) - dd = { } + print("%s%s [%s]" % (prefix, connection_to_str(connection), n)) + dd = {} if s_u is not None: dd = s_u.get_property(NM.SETTING_USER_DATA) for k in keys: @@ -145,7 +147,7 @@ def print_user_data(connection, data_allow_regex, data, prefix=''): else: print('%s MISSING: "%s"' % (prefix, k)) else: - assert(v == dd.get(k, None)) + assert v == dd.get(k, None) print('%s SET: "%s" = "%s"' % (prefix, k, v)) else: print('%s MISSING: "%s"' % (prefix, k)) @@ -155,20 +157,19 @@ def do_get(connections, data): first_line = True connections = list(connections) if not connections: - print('no matching connections (use id|uuid argument)') + print("no matching connections (use id|uuid argument)") sys.exit(1) for c in connections: if first_line: first_line = False else: - print('') + print("") print_user_data(c, True, data) + def do_set(connection, data, set_gobject): - print_user_data(connection, False, - [d[0] for d in data], - prefix = 'BEFORE: ') - print('') + print_user_data(connection, False, [d[0] for d in data], prefix="BEFORE: ") + print("") s_u = connection.get_setting(NM.SettingUser) if s_u is None: connection.add_setting(NM.SettingUser()) @@ -197,35 +198,37 @@ def do_set(connection, data, set_gobject): print('error setting key "%s" = "%s": %s' % (key, val, e)) sys.exit(1) - try: connection.commit_changes(True, None) except Exception as e: - print('failure to commit connection: %s' % (e)) + print("failure to commit connection: %s" % (e)) sys.exit(1) - print('') - print_user_data(connection, False, - [d[0] for d in data], - prefix = 'AFTER: ') + print("") + print_user_data(connection, False, [d[0] for d in data], prefix="AFTER: ") + ############################################################################### -if __name__ == '__main__': +if __name__ == "__main__": args = parse_args() nm_client = NM.Client.new(None) - connections = connections_filter(nm_client.get_connections(), args['filter']) + connections = connections_filter(nm_client.get_connections(), args["filter"]) - if args['set']: - if not args['data']: - print('Requires one or more arguments to set or delete') + if args["set"]: + if not args["data"]: + print("Requires one or more arguments to set or delete") sys.exit(1) if len(connections) != 1: - print('To set the user-data of a connection, exactly one connection must be selected via id|uuid. Instead, %s connection matched ([%s])' % - (len(connections), ', '.join([connection_to_str(c) for c in connections]))) + print( + "To set the user-data of a connection, exactly one connection must be selected via id|uuid. Instead, %s connection matched ([%s])" + % ( + len(connections), + ", ".join([connection_to_str(c) for c in connections]), + ) + ) sys.exit(1) - do_set(connections[0], args['data'], args['set-gobject']) + do_set(connections[0], args["data"], args["set-gobject"]) else: - do_get(connections, args['data']) - + do_get(connections, args["data"]) diff --git a/examples/python/gi/show-wifi-networks.py b/examples/python/gi/show-wifi-networks.py index e1ee4c3d5d..b865a85aa4 100755 --- a/examples/python/gi/show-wifi-networks.py +++ b/examples/python/gi/show-wifi-networks.py @@ -7,7 +7,8 @@ import locale import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import NM # @@ -19,40 +20,50 @@ from gi.repository import NM # an error without it: http://www.python.org/dev/peps/pep-0263/ # + def clamp(value, minvalue, maxvalue): return max(minvalue, min(value, maxvalue)) + def ssid_to_utf8(ap): ssid = ap.get_ssid() if not ssid: return "" return NM.utils_ssid_to_utf8(ap.get_ssid().get_data()) + def print_device_info(device): active_ap = dev.get_active_access_point() ssid = None if active_ap is not None: ssid = ssid_to_utf8(active_ap) - info = "Device: %s | Driver: %s | Active AP: %s" % (dev.get_iface(), dev.get_driver(), ssid) + info = "Device: %s | Driver: %s | Active AP: %s" % ( + dev.get_iface(), + dev.get_driver(), + ssid, + ) print(info) - print('=' * len(info)) + print("=" * len(info)) + def mode_to_string(mode): - if mode == getattr(NM, '80211Mode').INFRA: + if mode == getattr(NM, "80211Mode").INFRA: return "INFRA" - if mode == getattr(NM, '80211Mode').ADHOC: + if mode == getattr(NM, "80211Mode").ADHOC: return "ADHOC" - if mode == getattr(NM, '80211Mode').AP: + if mode == getattr(NM, "80211Mode").AP: return "AP" return "UNKNOWN" + def flags_to_string(flags): - if flags & getattr(NM, '80211ApFlags').PRIVACY: + if flags & getattr(NM, "80211ApFlags").PRIVACY: return "PRIVACY" return "NONE" + def security_flags_to_string(flags): - NM_AP_FLAGS = getattr(NM, '80211ApSecurityFlags') + NM_AP_FLAGS = getattr(NM, "80211ApSecurityFlags") str = "" if flags & NM_AP_FLAGS.PAIR_WEP40: str = str + " PAIR_WEP40" @@ -79,43 +90,50 @@ def security_flags_to_string(flags): else: return "NONE" + def flags_to_security(flags, wpa_flags, rsn_flags): str = "" - if ((flags & getattr(NM, '80211ApFlags').PRIVACY) and - (wpa_flags == 0) and (rsn_flags == 0)): - str = str + " WEP" + if ( + (flags & getattr(NM, "80211ApFlags").PRIVACY) + and (wpa_flags == 0) + and (rsn_flags == 0) + ): + str = str + " WEP" if wpa_flags != 0: str = str + " WPA1" if rsn_flags != 0: str = str + " WPA2" - if ((wpa_flags & getattr(NM, '80211ApSecurityFlags').KEY_MGMT_802_1X) or - (rsn_flags & getattr(NM, '80211ApSecurityFlags').KEY_MGMT_802_1X)): + if (wpa_flags & getattr(NM, "80211ApSecurityFlags").KEY_MGMT_802_1X) or ( + rsn_flags & getattr(NM, "80211ApSecurityFlags").KEY_MGMT_802_1X + ): str = str + " 802.1X" return str.lstrip() + def print_ap_info(ap): strength = ap.get_strength() frequency = ap.get_frequency() flags = ap.get_flags() wpa_flags = ap.get_wpa_flags() rsn_flags = ap.get_rsn_flags() - print("SSID: %s" % (ssid_to_utf8(ap))) - print("BSSID: %s" % (ap.get_bssid())) - print("Frequency: %s" % (frequency)) - print("Channel: %s" % (NM.utils_wifi_freq_to_channel(frequency))) - print("Mode: %s" % (mode_to_string(ap.get_mode()))) - print("Flags: %s" % (flags_to_string(flags))) - print("WPA flags: %s" % (security_flags_to_string(wpa_flags))) - print("RSN flags: %s" % (security_flags_to_string(rsn_flags))) - print("Security: %s" % (flags_to_security(flags, wpa_flags, rsn_flags))) + print("SSID: %s" % (ssid_to_utf8(ap))) + print("BSSID: %s" % (ap.get_bssid())) + print("Frequency: %s" % (frequency)) + print("Channel: %s" % (NM.utils_wifi_freq_to_channel(frequency))) + print("Mode: %s" % (mode_to_string(ap.get_mode()))) + print("Flags: %s" % (flags_to_string(flags))) + print("WPA flags: %s" % (security_flags_to_string(wpa_flags))) + print("RSN flags: %s" % (security_flags_to_string(rsn_flags))) + print("Security: %s" % (flags_to_security(flags, wpa_flags, rsn_flags))) print("Strength: %s %s%%" % (NM.utils_wifi_strength_bars(strength), strength)) print + if __name__ == "__main__": # Python apparently doesn't call setlocale() on its own? We have to call this or else # NM.utils_wifi_strength_bars() will think the locale is ASCII-only, and return the # fallback characters rather than the unicode bars - locale.setlocale(locale.LC_ALL, '') + locale.setlocale(locale.LC_ALL, "") nmc = NM.Client.new(None) devs = nmc.get_devices() @@ -125,4 +143,3 @@ if __name__ == "__main__": print_device_info(dev) for ap in dev.get_access_points(): print_ap_info(ap) - diff --git a/examples/python/gi/update-ip4-method.py b/examples/python/gi/update-ip4-method.py index 9bba619918..6fae260353 100755 --- a/examples/python/gi/update-ip4-method.py +++ b/examples/python/gi/update-ip4-method.py @@ -13,7 +13,8 @@ # import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM import sys, socket @@ -25,7 +26,9 @@ if __name__ == "__main__": 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])) + print( + "Usage: %s %s static address prefix [gateway]" % (sys.argv[0], sys.argv[1]) + ) sys.exit(1) uuid = sys.argv[1] @@ -69,4 +72,3 @@ if __name__ == "__main__": except Exception as e: sys.stderr.write("Error: %s\n" % e) break - diff --git a/examples/python/gi/vpn-import.py b/examples/python/gi/vpn-import.py index 78ae7cb182..a7c2f7f3d3 100755 --- a/examples/python/gi/vpn-import.py +++ b/examples/python/gi/vpn-import.py @@ -9,7 +9,8 @@ # VPN plugin. import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM import sys @@ -35,17 +36,21 @@ for vpn_info in NM.VpnPluginInfo.list_load(): break if connection is None: - print("None of the VPN plugins was able to import \"%s\"" % (filename)) + print('None of the VPN plugins was able to import "%s"' % (filename)) sys.exit(1) connection.normalize() -print("connection imported from \"%s\" using plugin \"%s\" (\"%s\", %s)" % (filename, vpn_info.get_filename(), connection.get_id(), connection.get_uuid())) +print( + 'connection imported from "%s" using plugin "%s" ("%s", %s)' + % (filename, vpn_info.get_filename(), connection.get_id(), connection.get_uuid()) +) client = NM.Client.new(None) main_loop = GLib.MainLoop() + def added_cb(client, result, data): try: client.add_connection_finish(result) @@ -54,6 +59,7 @@ def added_cb(client, result, data): print("ERROR: failed to add connection: %s\n" % e) main_loop.quit() + client.add_connection_async(connection, True, None, added_cb, None) main_loop.run() diff --git a/examples/python/gi/wifi-p2p.py b/examples/python/gi/wifi-p2p.py index 804df34c89..526db5ecab 100755 --- a/examples/python/gi/wifi-p2p.py +++ b/examples/python/gi/wifi-p2p.py @@ -9,12 +9,14 @@ import sys import uuid import gi -gi.require_version('NM', '1.0') + +gi.require_version("NM", "1.0") from gi.repository import GLib, NM main_loop = None client = None + def create_profile(name, peer_mac): profile = NM.SimpleConnection.new() @@ -32,8 +34,10 @@ def create_profile(name, peer_mac): s_wifi_p2p = NM.SettingWifiP2P.new() s_wifi_p2p.set_property(NM.SETTING_WIFI_P2P_PEER, peer_mac) - s_wifi_p2p.set_property(NM.SETTING_WIFI_P2P_WFD_IES, - GLib.Bytes.new(b'\x00\x00\x06\x00\x90\x1c\x44\x00\xc8')) + s_wifi_p2p.set_property( + NM.SETTING_WIFI_P2P_WFD_IES, + GLib.Bytes.new(b"\x00\x00\x06\x00\x90\x1c\x44\x00\xc8"), + ) profile.add_setting(s_con) profile.add_setting(s_ip4) @@ -42,6 +46,7 @@ def create_profile(name, peer_mac): return profile + def activated_cb(client, result, data): try: client.add_and_activate_connection2_finish(result) @@ -50,35 +55,37 @@ def activated_cb(client, result, data): sys.stderr.write("Error: %s\n" % e) main_loop.quit() + def scan_timeout_cb(device): peers = device.get_peers() if len(peers) == 0: main_loop.quit() sys.exit("No peer found") - print("\n {:20} {:30} {:3} {:30}".format("MAC", "Name", "Sig", "Wfd-IEs")); + print("\n {:20} {:30} {:3} {:30}".format("MAC", "Name", "Sig", "Wfd-IEs")) for p in peers: if p.get_wfd_ies() is not None: ies = p.get_wfd_ies().get_data().hex() else: ies = "" - print(" {:20} {:30} {:3} {:30}".format(p.get_hw_address(), - p.get_name(), - p.get_strength(), - ies)) + print( + " {:20} {:30} {:3} {:30}".format( + p.get_hw_address(), p.get_name(), p.get_strength(), ies + ) + ) print("") # Connect to first peer - profile = create_profile('P2P-connection', peers[0].get_hw_address()) - client.add_and_activate_connection2(profile, - device, - "/", - GLib.Variant('a{sv}', {}), - None, - activated_cb, - None) - print(" * Connecting to peer {} using profile '{}'".format(peers[0].get_hw_address(), - profile.get_id())) + profile = create_profile("P2P-connection", peers[0].get_hw_address()) + client.add_and_activate_connection2( + profile, device, "/", GLib.Variant("a{sv}", {}), None, activated_cb, None + ) + print( + " * Connecting to peer {} using profile '{}'".format( + peers[0].get_hw_address(), profile.get_id() + ) + ) + def start_find_cb(device, async_result, user_data): try: @@ -87,9 +94,10 @@ def start_find_cb(device, async_result, user_data): sys.stderr.write("Error: %s\n" % e) main_loop.quit() - print(" * Scanning on device {}...".format(device.get_iface())); + print(" * Scanning on device {}...".format(device.get_iface())) GLib.timeout_add(10000, scan_timeout_cb, device) + if __name__ == "__main__": client = NM.Client.new(None) device = None @@ -103,7 +111,7 @@ if __name__ == "__main__": if device is None: sys.exit("No Wi-Fi P2P device found") - device.start_find(GLib.Variant('a{sv}', {}), None, start_find_cb, None) + device.start_find(GLib.Variant("a{sv}", {}), None, start_find_cb, None) main_loop = GLib.MainLoop() main_loop.run() |