all: reformat python files with python black

Part of !537.

https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/merge_requests/537
This commit is contained in:
Sayed Shah
2020-06-09 16:28:32 -04:00
committed by Thomas Haller
parent b6febb0fd0
commit be822b52e6
44 changed files with 3179 additions and 1961 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -20,34 +20,40 @@ import socket, struct, dbus, uuid
def ip_to_int(ip_string): def ip_to_int(ip_string):
return struct.unpack("=I", socket.inet_aton(ip_string))[0] return struct.unpack("=I", socket.inet_aton(ip_string))[0]
def int_to_ip(ip_int): def int_to_ip(ip_int):
return socket.inet_ntoa(struct.pack("=I", 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_wired = dbus.Dictionary({"duplex": "full"})
s_ip4 = dbus.Dictionary({ s_con = dbus.Dictionary(
'addresses': dbus.Array([addr1], signature=dbus.Signature('au')), {"type": "802-3-ethernet", "uuid": str(uuid.uuid4()), "id": "MyConnectionExample"}
'method': 'manual'}) )
s_ip6 = dbus.Dictionary({'method': 'ignore'}) 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",
}
)
con = dbus.Dictionary({ s_ip6 = dbus.Dictionary({"method": "ignore"})
'802-3-ethernet': s_wired,
'connection': s_con, con = dbus.Dictionary(
'ipv4': s_ip4, {"802-3-ethernet": s_wired, "connection": s_con, "ipv4": s_ip4, "ipv6": s_ip6}
'ipv6': s_ip6}) )
print("Creating connection:", s_con['id'], "-", s_con['uuid']) print("Creating connection:", s_con["id"], "-", s_con["uuid"])
bus = dbus.SystemBus() 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 = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
settings.AddConnection(con) settings.AddConnection(con)

View File

@@ -17,34 +17,33 @@
import dbus, uuid import dbus, uuid
s_wired = dbus.Dictionary({'duplex': 'full'}) s_wired = dbus.Dictionary({"duplex": "full"})
s_con = dbus.Dictionary({ s_con = dbus.Dictionary(
'type': '802-3-ethernet', {"type": "802-3-ethernet", "uuid": str(uuid.uuid4()), "id": "MyConnectionExample"}
'uuid': str(uuid.uuid4()), )
'id': 'MyConnectionExample'})
addr1 = dbus.Dictionary({ addr1 = dbus.Dictionary({"address": "10.1.2.3", "prefix": dbus.UInt32(8)})
'address': '10.1.2.3', s_ip4 = dbus.Dictionary(
'prefix': dbus.UInt32(8)}) {
s_ip4 = dbus.Dictionary({ "address-data": dbus.Array([addr1], signature=dbus.Signature("a{sv}")),
'address-data': dbus.Array([addr1], signature=dbus.Signature('a{sv}')), "gateway": "10.1.2.1",
'gateway': '10.1.2.1', "method": "manual",
'method': 'manual'}) }
)
s_ip6 = dbus.Dictionary({'method': 'ignore'}) s_ip6 = dbus.Dictionary({"method": "ignore"})
con = dbus.Dictionary({ con = dbus.Dictionary(
'802-3-ethernet': s_wired, {"802-3-ethernet": s_wired, "connection": s_con, "ipv4": s_ip4, "ipv6": s_ip6}
'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() 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 = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
settings.AddConnection(con) settings.AddConnection(con)

View File

@@ -6,45 +6,57 @@
import dbus, uuid import dbus, uuid
def path_to_value(path): def path_to_value(path):
return dbus.ByteArray("file://".encode("utf-8") + path.encode("utf-8") + "\0".encode("utf-8")) 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({ s_con = dbus.Dictionary(
'ssid': dbus.ByteArray("homewifi".encode("utf-8")), {"type": "802-11-wireless", "uuid": str(uuid.uuid4()), "id": "My Wifi"}
'security': '802-11-wireless-security'}) )
s_wsec = dbus.Dictionary({'key-mgmt': 'wpa-eap'}) s_wifi = dbus.Dictionary(
{
"ssid": dbus.ByteArray("homewifi".encode("utf-8")),
"security": "802-11-wireless-security",
}
)
s_8021x = dbus.Dictionary({ s_wsec = dbus.Dictionary({"key-mgmt": "wpa-eap"})
'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_8021x = dbus.Dictionary(
s_ip6 = dbus.Dictionary({'method': 'ignore'}) {
"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",
}
)
con = dbus.Dictionary({ s_ip4 = dbus.Dictionary({"method": "auto"})
'connection': s_con, s_ip6 = dbus.Dictionary({"method": "ignore"})
'802-11-wireless': s_wifi,
'802-11-wireless-security': s_wsec, con = dbus.Dictionary(
'802-1x': s_8021x, {
'ipv4': s_ip4, "connection": s_con,
'ipv6': s_ip6 "802-11-wireless": s_wifi,
}) "802-11-wireless-security": s_wsec,
"802-1x": s_8021x,
"ipv4": s_ip4,
"ipv6": s_ip6,
}
)
bus = dbus.SystemBus() 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 = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
settings.AddConnection(con) settings.AddConnection(con)

View File

@@ -6,38 +6,37 @@
import dbus, uuid import dbus, uuid
s_con = dbus.Dictionary({ s_con = dbus.Dictionary(
'type': '802-11-wireless', {"type": "802-11-wireless", "uuid": str(uuid.uuid4()), "id": "My-WPA-PSK"}
'uuid': str(uuid.uuid4()), )
'id': 'My-WPA-PSK'})
s_wifi = dbus.Dictionary({ s_wifi = dbus.Dictionary(
'ssid': dbus.ByteArray("best-wifi".encode("utf-8")), {"ssid": dbus.ByteArray("best-wifi".encode("utf-8")), "mode": "infrastructure",}
'mode': 'infrastructure', )
})
s_wsec = dbus.Dictionary({ s_wsec = dbus.Dictionary(
'key-mgmt': 'wpa-psk', {"key-mgmt": "wpa-psk", "auth-alg": "open", "psk": "super-secret-password",}
'auth-alg': 'open', )
'psk': 'super-secret-password',
})
s_ip4 = dbus.Dictionary({'method': 'auto'}) s_ip4 = dbus.Dictionary({"method": "auto"})
s_ip6 = dbus.Dictionary({'method': 'ignore'}) s_ip6 = dbus.Dictionary({"method": "ignore"})
con = dbus.Dictionary({ con = dbus.Dictionary(
'connection': s_con, {
'802-11-wireless': s_wifi, "connection": s_con,
'802-11-wireless-security': s_wsec, "802-11-wireless": s_wifi,
'ipv4': s_ip4, "802-11-wireless-security": s_wsec,
'ipv6': s_ip6 "ipv4": s_ip4,
}) "ipv6": s_ip6,
}
)
bus = dbus.SystemBus() 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 = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
settings.AddConnection(con) settings.AddConnection(con)

View File

@@ -12,14 +12,18 @@ import dbus, sys
# Get a proxy for the base NetworkManager object # Get a proxy for the base NetworkManager object
bus = dbus.SystemBus() 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") manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
allDevs = manager.GetDevices() allDevs = manager.GetDevices()
def Usage(): def Usage():
print "Usage: %s <ROLLBACK-INTERVAL> [INTERFACE]..." % sys.argv[0] print "Usage: %s <ROLLBACK-INTERVAL> [INTERFACE]..." % sys.argv[0]
sys.exit(1) sys.exit(1)
def GetDevicePath(ifname): def GetDevicePath(ifname):
for dev in allDevs: for dev in allDevs:
dev_proxy = bus.get_object("org.freedesktop.NetworkManager", dev) dev_proxy = bus.get_object("org.freedesktop.NetworkManager", dev)
@@ -29,6 +33,7 @@ def GetDevicePath(ifname):
return dev return dev
return return
if len(sys.argv) < 2: if len(sys.argv) < 2:
Usage() Usage()
@@ -46,12 +51,11 @@ for arg in sys.argv[2:]:
else: else:
devList.append(path) devList.append(path)
checkpoint = manager.CheckpointCreate(devList, checkpoint = manager.CheckpointCreate(devList, interval, 1)
interval, # DESTROY_ALL
1); # DESTROY_ALL
choice = raw_input('Do you want to rollback [y/n]? ').lower() choice = raw_input("Do you want to rollback [y/n]? ").lower()
if choice == 'y': if choice == "y":
print "Rollback checkpoint" print "Rollback checkpoint"
results = manager.CheckpointRollback(checkpoint) results = manager.CheckpointRollback(checkpoint)
for d in results: for d in results:

View File

@@ -17,51 +17,59 @@ from gi.repository import GObject
DBusGMainLoop(set_as_default=True) DBusGMainLoop(set_as_default=True)
def add_connection(con): def add_connection(con):
bus = dbus.SystemBus() 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 = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
return settings.AddConnection(con) 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({ def create_bond(bond_name):
'bond': s_bond, bond_opts = dbus.Dictionary({"mode": "4"})
'connection': s_con, s_bond = dbus.Dictionary({"options": bond_opts})
'ipv4': s_ip4, s_con = dbus.Dictionary(
'ipv6': s_ip6}) {
"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) print("Creating bond connection: %s" % bond_name)
return add_connection(con) 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({ def create_slave(device, master):
'802-3-ethernet': s_wired, slave_name = "bond-" + master + "-slave-" + device
'connection': s_con}) 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) print("Creating slave connection: %s" % slave_name)
add_connection(con) add_connection(con)
def usage(): def usage():
print("Usage: %s <bond_name> <ifname1> ..." % sys.argv[0]) print("Usage: %s <bond_name> <ifname1> ..." % sys.argv[0])
sys.exit(0) sys.exit(0)
@@ -78,22 +86,27 @@ for ifname in sys.argv[2:]:
# Activate the bond # Activate the bond
bus = dbus.SystemBus() 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") manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
ac = manager.ActivateConnection(bond_path, "/", "/") ac = manager.ActivateConnection(bond_path, "/", "/")
print("Activating bond: %s (%s)" % (bond_name, ac)) print("Activating bond: %s (%s)" % (bond_name, ac))
# Monitor the active bond connection # Monitor the active bond connection
loop = GObject.MainLoop() loop = GObject.MainLoop()
def properties_changed(props): def properties_changed(props):
if 'State' in props: if "State" in props:
if props['State'] == 2: if props["State"] == 2:
print("Successfully connected") print("Successfully connected")
loop.quit() loop.quit()
if props['State'] == 3 or props['State'] == 4: if props["State"] == 3 or props["State"] == 4:
print("Bond activation failed") print("Bond activation failed")
loop.quit() loop.quit()
obj = bus.get_object("org.freedesktop.NetworkManager", ac) obj = bus.get_object("org.freedesktop.NetworkManager", ac)
iface = dbus.Interface(obj, "org.freedesktop.NetworkManager.Connection.Active") iface = dbus.Interface(obj, "org.freedesktop.NetworkManager.Connection.Active")
iface.connect_to_signal("PropertiesChanged", properties_changed) iface.connect_to_signal("PropertiesChanged", properties_changed)

View File

@@ -16,7 +16,9 @@ if len(sys.argv) != 2:
bus = dbus.SystemBus() bus = dbus.SystemBus()
# Get a proxy for the base NetworkManager object # 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") manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
dpath = None dpath = None
@@ -45,4 +47,3 @@ if state <= 3:
# Tell NM to disconnect it # Tell NM to disconnect it
dev_iface.Disconnect() dev_iface.Disconnect()

View File

@@ -13,11 +13,15 @@ import dbus
bus = dbus.SystemBus() bus = dbus.SystemBus()
# Get a proxy for the base NetworkManager object # 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") manager = dbus.Interface(m_proxy, "org.freedesktop.NetworkManager")
mgr_props = dbus.Interface(m_proxy, "org.freedesktop.DBus.Properties") 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") settings = dbus.Interface(s_proxy, "org.freedesktop.NetworkManager.Settings")
# Find the device the user wants to disconnect # 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") uuid = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Uuid")
# Grab the connection object path so we can get all the connection's settings # 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) 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() 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: if len(active) == 0:
print("No active connections") print("No active connections")

View File

@@ -30,8 +30,9 @@ proxy = bus.get_object(NM_SERVICE_NAME, "/org/freedesktop/NetworkManager")
manager = dbus.Interface(proxy, NM_MANAGER_IFACE) manager = dbus.Interface(proxy, NM_MANAGER_IFACE)
props = dbus.Interface(proxy, DBUS_PROPS_IFACE) props = dbus.Interface(proxy, DBUS_PROPS_IFACE)
def found_connection_type(ctype): def found_connection_type(ctype):
if ctype == '': if ctype == "":
print("No active connection") print("No active connection")
elif ctype in ["gsm", "cdma", "bluetooth"]: elif ctype in ["gsm", "cdma", "bluetooth"]:
print("WWAN is default") print("WWAN is default")
@@ -39,6 +40,7 @@ def found_connection_type(ctype):
print("WWAN is not default") print("WWAN is not default")
sys.exit(0) sys.exit(0)
# Shortcut #1, for NM 1.0 # Shortcut #1, for NM 1.0
try: try:
ctype = props.Get(NM_MANAGER_IFACE, "PrimaryConnectionType") ctype = props.Get(NM_MANAGER_IFACE, "PrimaryConnectionType")
@@ -50,7 +52,7 @@ except KeyError:
try: try:
primary = props.Get(NM_MANAGER_IFACE, "PrimaryConnection") primary = props.Get(NM_MANAGER_IFACE, "PrimaryConnection")
if not primary: if not primary:
found_connection_type('') found_connection_type("")
primary_proxy = bus.get_object(NM_SERVICE_NAME, primary) primary_proxy = bus.get_object(NM_SERVICE_NAME, primary)
primary_props = dbus.Interface(primary_proxy, DBUS_PROPS_IFACE) primary_props = dbus.Interface(primary_proxy, DBUS_PROPS_IFACE)
ctype = primary_props.Get(NM_ACTIVE_CONNECTION_INTERFACE, "Type") ctype = primary_props.Get(NM_ACTIVE_CONNECTION_INTERFACE, "Type")
@@ -83,4 +85,3 @@ if default_is_wwan:
print("WWAN is default") print("WWAN is default")
else: else:
print("WWAN is not default") print("WWAN is not default")

View File

@@ -12,6 +12,7 @@ import dbus
bus = dbus.SystemBus() bus = dbus.SystemBus()
def merge_secrets(proxy, config, setting_name): def merge_secrets(proxy, config, setting_name):
try: try:
# returns a dict of dicts mapping name::setting, where setting is a dict # 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: except Exception as e:
pass pass
def dict_to_string(d, indent): def dict_to_string(d, indent):
# Try to trivially translate a dictionary's elements into nice string # Try to trivially translate a dictionary's elements into nice string
# formatting. # formatting.
@@ -48,6 +50,7 @@ def dict_to_string(d, indent):
dstr += "%s%s: %s\n" % (indent, key, str_val) dstr += "%s%s: %s\n" % (indent, key, str_val)
return dstr return dstr
def connection_to_string(config): def connection_to_string(config):
# dump a connection configuration to a the console # dump a connection configuration to a the console
for setting_name in config: for setting_name in config:
@@ -66,29 +69,31 @@ def print_connections():
# List each connection's name, UUID, and type # List each connection's name, UUID, and type
for path in connection_paths: for path in connection_paths:
con_proxy = bus.get_object(service_name, path) 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() config = settings_connection.GetSettings()
# Now get secrets too; we grab the secrets for each type of connection # 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 # (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 # you only need 'wifi' secrets or '802.1x' secrets, not everything) and
# merge that into the configuration data # merge that into the configuration data
merge_secrets(settings_connection, config, '802-11-wireless') merge_secrets(settings_connection, config, "802-11-wireless")
merge_secrets(settings_connection, config, '802-11-wireless-security') merge_secrets(settings_connection, config, "802-11-wireless-security")
merge_secrets(settings_connection, config, '802-1x') merge_secrets(settings_connection, config, "802-1x")
merge_secrets(settings_connection, config, 'gsm') merge_secrets(settings_connection, config, "gsm")
merge_secrets(settings_connection, config, 'cdma') merge_secrets(settings_connection, config, "cdma")
merge_secrets(settings_connection, config, 'ppp') merge_secrets(settings_connection, config, "ppp")
# Get the details of the 'connection' setting # Get the details of the 'connection' setting
s_con = config['connection'] s_con = config["connection"]
print(" name: %s" % s_con['id']) print(" name: %s" % s_con["id"])
print(" uuid: %s" % s_con['uuid']) print(" uuid: %s" % s_con["uuid"])
print(" type: %s" % s_con['type']) print(" type: %s" % s_con["type"])
print(" ------------------------------------------") print(" ------------------------------------------")
connection_to_string(config) connection_to_string(config)
print("") print("")
print_connections()
print_connections()

View File

@@ -9,44 +9,49 @@ import dbus
# This example lists basic information about network interfaces known to NM # This example lists basic information about network interfaces known to NM
# For the types see include/NetworkManager.h # For the types see include/NetworkManager.h
devtypes = { 1: "Ethernet", devtypes = {
2: "Wi-Fi", 1: "Ethernet",
5: "Bluetooth", 2: "Wi-Fi",
6: "OLPC", 5: "Bluetooth",
7: "WiMAX", 6: "OLPC",
8: "Modem", 7: "WiMAX",
9: "InfiniBand", 8: "Modem",
10: "Bond", 9: "InfiniBand",
11: "VLAN", 10: "Bond",
12: "ADSL", 11: "VLAN",
13: "Bridge", 12: "ADSL",
14: "Generic", 13: "Bridge",
15: "Team", 14: "Generic",
16: "TUN", 15: "Team",
17: "IPTunnel", 16: "TUN",
18: "MACVLAN", 17: "IPTunnel",
19: "VXLAN", 18: "MACVLAN",
20: "Veth" 19: "VXLAN",
} 20: "Veth",
}
states = { 0: "Unknown", states = {
10: "Unmanaged", 0: "Unknown",
20: "Unavailable", 10: "Unmanaged",
30: "Disconnected", 20: "Unavailable",
40: "Prepare", 30: "Disconnected",
50: "Config", 40: "Prepare",
60: "Need Auth", 50: "Config",
70: "IP Config", 60: "Need Auth",
80: "IP Check", 70: "IP Config",
90: "Secondaries", 80: "IP Check",
100: "Activated", 90: "Secondaries",
110: "Deactivating", 100: "Activated",
120: "Failed" } 110: "Deactivating",
120: "Failed",
}
bus = dbus.SystemBus() bus = dbus.SystemBus()
# Get a proxy for the base NetworkManager object # 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") manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
# Get all devices known to NM and print their properties # 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") props = prop_iface.GetAll("org.freedesktop.NetworkManager.Device")
print("============================") print("============================")
print("Interface: %s" % props['Interface']) print("Interface: %s" % props["Interface"])
try: try:
devtype = devtypes[props['DeviceType']] devtype = devtypes[props["DeviceType"]]
except KeyError: except KeyError:
devtype = "Unknown" devtype = "Unknown"
print("Type: %s" % devtype) print("Type: %s" % devtype)
print("Driver: %s" % props['Driver']) print("Driver: %s" % props["Driver"])
try: try:
state = states[props['State']] state = states[props["State"]]
except KeyError: except KeyError:
state = "Unknown" state = "Unknown"
print("State: %s" % state) print("State: %s" % state)

View File

@@ -7,38 +7,46 @@
import dbus import dbus
# Device states from include/NetworkManager.h # Device states from include/NetworkManager.h
device_states = { 0: "Unknown", device_states = {
10: "Unmanaged", 0: "Unknown",
20: "Unavailable", 10: "Unmanaged",
30: "Disconnected", 20: "Unavailable",
40: "Prepare", 30: "Disconnected",
50: "Config", 40: "Prepare",
60: "Need Auth", 50: "Config",
70: "IP Config", 60: "Need Auth",
80: "IP Check", 70: "IP Config",
90: "Secondaries", 80: "IP Check",
100: "Activated", 90: "Secondaries",
110: "Deactivating", 100: "Activated",
120: "Failed" } 110: "Deactivating",
120: "Failed",
}
connectivity_states = { 0: "Unknown", connectivity_states = {
1: "Activating", 0: "Unknown",
2: "Activated", 1: "Activating",
3: "Deactivating", 2: "Activated",
4: "Deactivated" } 3: "Deactivating",
4: "Deactivated",
}
nm_state = { 0: "Unknown", nm_state = {
10: "Asleep", 0: "Unknown",
20: "Disconnected", 10: "Asleep",
30: "Disconnecting", 20: "Disconnected",
40: "Connecting", 30: "Disconnecting",
50: "Connected-Local", 40: "Connecting",
60: "Connected-Site", 50: "Connected-Local",
70: "Connected-Global" } 60: "Connected-Site",
70: "Connected-Global",
}
bus = dbus.SystemBus() 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") manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
# Get overall NM connection state # Get overall NM connection state
@@ -55,7 +63,7 @@ for d in devices:
name = prop_iface.Get("org.freedesktop.NetworkManager.Device", "Interface") name = prop_iface.Get("org.freedesktop.NetworkManager.Device", "Interface")
# and print them out # and print them out
if state == 100 : # activated if state == 100: # activated
print("Device %s is activated" % name) print("Device %s is activated" % name)
else: else:
print("Device %s is not activated (state=%s)" % (name, device_states[state])) 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 # Connections in NM are a collection of settings that describe everything
# needed to connect to a specific network. Lets get those details so we # needed to connect to a specific network. Lets get those details so we
# can find the user-readable name of the connection. # 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) 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_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())) print("Connection '%s' is %s" % (con_name, connectivity_states[state].lower()))

View File

@@ -14,7 +14,9 @@ import dbus
bus = dbus.SystemBus() bus = dbus.SystemBus()
# Get a proxy for the base NetworkManager object # 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") manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
all_aps = [] all_aps = []
@@ -35,20 +37,26 @@ for d in devices:
# Get device's type; we only want wifi devices # Get device's type; we only want wifi devices
iface = prop_iface.Get("org.freedesktop.NetworkManager.Device", "Interface") iface = prop_iface.Get("org.freedesktop.NetworkManager.Device", "Interface")
dtype = prop_iface.Get("org.freedesktop.NetworkManager.Device", "DeviceType") dtype = prop_iface.Get("org.freedesktop.NetworkManager.Device", "DeviceType")
if dtype == 2: # WiFi if dtype == 2: # WiFi
# Get a proxy for the wifi interface # 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") wifi_prop_iface = dbus.Interface(dev_proxy, "org.freedesktop.DBus.Properties")
# Get the associated AP's object path # 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 # Get all APs the card can see
aps = wifi_iface.GetAccessPoints() aps = wifi_iface.GetAccessPoints()
for path in aps: for path in aps:
ap_proxy = bus.get_object("org.freedesktop.NetworkManager", path) ap_proxy = bus.get_object("org.freedesktop.NetworkManager", path)
ap_prop_iface = dbus.Interface(ap_proxy, "org.freedesktop.DBus.Properties") 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 # Cache the BSSID
if not bssid in all_aps: if not bssid in all_aps:
@@ -62,4 +70,3 @@ for d in devices:
print("\nFound APs:") print("\nFound APs:")
for bssid in all_aps: for bssid in all_aps:
print(bssid) print(bssid)

View File

@@ -30,42 +30,49 @@ if method == "static":
method = "manual" method = "manual"
bus = dbus.SystemBus() 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 = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
for c_path in settings.ListConnections(): for c_path in settings.ListConnections():
c_proxy = bus.get_object("org.freedesktop.NetworkManager", c_path) 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() c_settings = c_obj.GetSettings()
# Look for the requested connection UUID # Look for the requested connection UUID
if c_settings['connection']['uuid'] != sys.argv[1]: if c_settings["connection"]["uuid"] != sys.argv[1]:
continue continue
# add IPv4 setting if it doesn't yet exist # add IPv4 setting if it doesn't yet exist
if 'ipv4' not in c_settings: if "ipv4" not in c_settings:
c_settings['ipv4'] = {} c_settings["ipv4"] = {}
# clear existing address info # clear existing address info
if c_settings['ipv4'].has_key('addresses'): if c_settings["ipv4"].has_key("addresses"):
del c_settings['ipv4']['addresses'] del c_settings["ipv4"]["addresses"]
if c_settings['ipv4'].has_key('address-data'): if c_settings["ipv4"].has_key("address-data"):
del c_settings['ipv4']['address-data'] del c_settings["ipv4"]["address-data"]
if c_settings['ipv4'].has_key('gateway'): if c_settings["ipv4"].has_key("gateway"):
del c_settings['ipv4']['gateway'] del c_settings["ipv4"]["gateway"]
# set the method and change properties # set the method and change properties
c_settings['ipv4']['method'] = method c_settings["ipv4"]["method"] = method
if method == "manual": if method == "manual":
# Add the static IP address, prefix, and (optional) gateway # Add the static IP address, prefix, and (optional) gateway
addr = dbus.Dictionary({'address': sys.argv[3], 'prefix': dbus.UInt32(int(sys.argv[4]))}) addr = dbus.Dictionary(
c_settings['ipv4']['address-data'] = dbus.Array([addr], signature=dbus.Signature('a{sv}')) {"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: 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 # Save all the updated settings back to NetworkManager
c_obj.Update(c_settings) c_obj.Update(c_settings)
break break
sys.exit(0) sys.exit(0)

View File

@@ -18,6 +18,7 @@ import sys
bus = dbus.SystemBus() bus = dbus.SystemBus()
def change_secrets_in_one_setting(proxy, config, setting_name): def change_secrets_in_one_setting(proxy, config, setting_name):
# Add new secret values to the connection config # Add new secret values to the connection config
try: 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 # Ask user for new secrets and put them into our connection config
for setting in secrets: for setting in secrets:
for key in secrets[setting]: 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 config[setting_name][key] = new_secret
except Exception as e: except Exception as e:
#code = str(e).split(':')[0] # code = str(e).split(':')[0]
#print("Exception:" + str(e)) # print("Exception:" + str(e))
pass pass
def change_secrets(con_path, config): def change_secrets(con_path, config):
# Get existing secrets; we grab the secrets for each type of connection # 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 # (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 # you only need 'wifi' secrets or '802.1x' secrets, not everything) and
# set new values into the connection settings (config) # set new values into the connection settings (config)
con_proxy = bus.get_object("org.freedesktop.NetworkManager", con_path) con_proxy = bus.get_object("org.freedesktop.NetworkManager", con_path)
connection_secrets = dbus.Interface(con_proxy, "org.freedesktop.NetworkManager.Settings.Connection") connection_secrets = dbus.Interface(
change_secrets_in_one_setting(connection_secrets, config, '802-11-wireless') con_proxy, "org.freedesktop.NetworkManager.Settings.Connection"
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, "802-11-wireless")
change_secrets_in_one_setting(connection_secrets, config, 'gsm') change_secrets_in_one_setting(
change_secrets_in_one_setting(connection_secrets, config, 'cdma') connection_secrets, config, "802-11-wireless-security"
change_secrets_in_one_setting(connection_secrets, config, 'ppp') )
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): def find_connection(name):
# Ask the settings service for the list of connections it provides # Ask the settings service for the list of connections it provides
global con_path 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") settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
connection_paths = settings.ListConnections() connection_paths = settings.ListConnections()
# Get the settings and look for connection's name # Get the settings and look for connection's name
for path in connection_paths: for path in connection_paths:
con_proxy = bus.get_object("org.freedesktop.NetworkManager", path) 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: try:
config = connection.GetSettings() config = connection.GetSettings()
except Exception as e: except Exception as e:
pass pass
# Find connection by the id # Find connection by the id
s_con = config['connection'] s_con = config["connection"]
if name == s_con['id']: if name == s_con["id"]:
con_path = path con_path = path
return config return config
# Find connection by the uuid # Find connection by the uuid
if name == s_con['uuid']: if name == s_con["uuid"]:
con_path = path con_path = path
return config return config
@@ -96,8 +109,9 @@ if con:
# Change the connection with Update() # Change the connection with Update()
proxy = bus.get_object("org.freedesktop.NetworkManager", con_path) 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) settings.Update(con)
else: else:
sys.exit("No connection '%s' found" % sys.argv[1]) sys.exit("No connection '%s' found" % sys.argv[1])

View File

@@ -8,11 +8,11 @@
# Run this script without any arguments to list the available connection uuids. # Run this script without any arguments to list the available connection uuids.
# The uuid of the connection to activate # 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 to use. Note that NM only allows the owner of the connection to activate it.
#UID=1000 # UID=1000
UID=0 UID = 0
import sys import sys
import os import os
@@ -22,20 +22,27 @@ import gobject
DBusGMainLoop(set_as_default=True) DBusGMainLoop(set_as_default=True)
def get_connections(): def get_connections():
bus = dbus.SystemBus() bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager/Settings') proxy = bus.get_object(
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings') "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings"
)
iface = dbus.Interface(
proxy, dbus_interface="org.freedesktop.NetworkManager.Settings"
)
return iface.ListConnections() return iface.ListConnections()
def get_connection_by_uuid(uuid): def get_connection_by_uuid(uuid):
bus = dbus.SystemBus() bus = dbus.SystemBus()
for c in get_connections(): for c in get_connections():
proxy = bus.get_object('org.freedesktop.NetworkManager', c) proxy = bus.get_object("org.freedesktop.NetworkManager", c)
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings.Connection') iface = dbus.Interface(
proxy, dbus_interface="org.freedesktop.NetworkManager.Settings.Connection"
)
settings = iface.GetSettings() settings = iface.GetSettings()
if settings['connection']['uuid'] == uuid: if settings["connection"]["uuid"] == uuid:
return c return c
return None return None
@@ -44,29 +51,39 @@ def get_connection_by_uuid(uuid):
def list_uuids(): def list_uuids():
bus = dbus.SystemBus() bus = dbus.SystemBus()
for c in get_connections(): for c in get_connections():
proxy = bus.get_object('org.freedesktop.NetworkManager', c) proxy = bus.get_object("org.freedesktop.NetworkManager", c)
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings.Connection') iface = dbus.Interface(
proxy, dbus_interface="org.freedesktop.NetworkManager.Settings.Connection"
)
settings = iface.GetSettings() settings = iface.GetSettings()
conn = settings['connection'] conn = settings["connection"]
print("%s - %s (%s)" % (conn['uuid'], conn['id'], conn['type'])) print("%s - %s (%s)" % (conn["uuid"], conn["id"], conn["type"]))
def get_active_connection_path(uuid): def get_active_connection_path(uuid):
bus = dbus.SystemBus() bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') proxy = bus.get_object(
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
active_connections = iface.Get('org.freedesktop.NetworkManager', 'ActiveConnections') )
iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.DBus.Properties")
active_connections = iface.Get(
"org.freedesktop.NetworkManager", "ActiveConnections"
)
for a in active_connections: for a in active_connections:
proxy = bus.get_object('org.freedesktop.NetworkManager', a) proxy = bus.get_object("org.freedesktop.NetworkManager", a)
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.DBus.Properties")
path = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection') path = iface.Get(
"org.freedesktop.NetworkManager.Connection.Active", "Connection"
)
proxy = bus.get_object('org.freedesktop.NetworkManager', path) proxy = bus.get_object("org.freedesktop.NetworkManager", path)
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings.Connection') iface = dbus.Interface(
proxy, dbus_interface="org.freedesktop.NetworkManager.Settings.Connection"
)
settings = iface.GetSettings() settings = iface.GetSettings()
if settings['connection']['uuid'] == uuid: if settings["connection"]["uuid"] == uuid:
return a return a
return None return None
@@ -74,19 +91,21 @@ def get_active_connection_path(uuid):
def get_wifi_device_path(): def get_wifi_device_path():
bus = dbus.SystemBus() bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') proxy = bus.get_object(
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager') "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
)
iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.NetworkManager")
devices = iface.GetDevices() devices = iface.GetDevices()
for d in devices: for d in devices:
proxy = bus.get_object('org.freedesktop.NetworkManager', d) proxy = bus.get_object("org.freedesktop.NetworkManager", d)
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.DBus.Properties")
devtype = iface.Get('org.freedesktop.NetworkManager.Device', 'DeviceType') devtype = iface.Get("org.freedesktop.NetworkManager.Device", "DeviceType")
if devtype == 2: if devtype == 2:
return d return d
return None return None
def activate_connection(connection_path, device_path):
def activate_connection(connection_path, device_path):
def reply_handler(opath): def reply_handler(opath):
print("Success: device activating") print("Success: device activating")
sys.exit(0) sys.exit(0)
@@ -96,14 +115,18 @@ def activate_connection(connection_path, device_path):
sys.exit(1) sys.exit(1)
bus = dbus.SystemBus() bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') proxy = bus.get_object(
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager') "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
iface.ActivateConnection('org.freedesktop.NetworkManager', )
connection_path, iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.NetworkManager")
device_path, iface.ActivateConnection(
"/", "org.freedesktop.NetworkManager",
reply_handler=reply_handler, connection_path,
error_handler=error_handler) device_path,
"/",
reply_handler=reply_handler,
error_handler=error_handler,
)
# Change the UID first if required # Change the UID first if required
@@ -135,4 +158,3 @@ print("Activating connection...")
activate_connection(connection_path, device_path) activate_connection(connection_path, device_path)
loop = gobject.MainLoop() loop = gobject.MainLoop()
loop.run() loop.run()

View File

@@ -31,7 +31,9 @@ devpath = nm.GetDeviceByIpIface(iface)
# Get a proxy to the wifi device and get the active access point's object path # Get a proxy to the wifi device and get the active access point's object path
proxy = bus.get_object(service_name, devpath) proxy = bus.get_object(service_name, devpath)
props = dbus.Interface(proxy, "org.freedesktop.DBus.Properties") 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 == "/": if active_ap_path == "/":
print("%s is not currently associated" % sys.argv[1]) print("%s is not currently associated" % sys.argv[1])
sys.exit(0) sys.exit(0)
@@ -50,4 +52,3 @@ for c in raw_ssid:
print("%s is associated to '%s' (%s)" % (sys.argv[1], ssid, bssid)) print("%s is associated to '%s' (%s)" % (sys.argv[1], ssid, bssid))
sys.exit(0) sys.exit(0)

View File

@@ -13,38 +13,42 @@
import dbus, sys, time import dbus, sys, time
our_uuid = '2b0d0f1d-b79d-43af-bde1-71744625642e' our_uuid = "2b0d0f1d-b79d-43af-bde1-71744625642e"
s_con = dbus.Dictionary({ s_con = dbus.Dictionary(
'type': '802-11-wireless', {"type": "802-11-wireless", "uuid": our_uuid, "id": "Test Hotspot"}
'uuid': our_uuid, )
'id': 'Test Hotspot'})
s_wifi = dbus.Dictionary({ s_wifi = dbus.Dictionary(
'ssid': dbus.ByteArray("My Hotspot".encode("utf-8")), {
'mode': "ap", "ssid": dbus.ByteArray("My Hotspot".encode("utf-8")),
'band': "bg", "mode": "ap",
'channel': dbus.UInt32(1)}) "band": "bg",
"channel": dbus.UInt32(1),
}
)
s_wsec = dbus.Dictionary({ s_wsec = dbus.Dictionary({"key-mgmt": "wpa-psk", "psk": "great password"})
'key-mgmt': 'wpa-psk',
'psk': 'great password'})
s_ip4 = dbus.Dictionary({'method': 'shared'}) s_ip4 = dbus.Dictionary({"method": "shared"})
s_ip6 = dbus.Dictionary({'method': 'ignore'}) 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,
}
)
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(): def usage():
print("Usage: %s <ifname> [up|down]" % sys.argv[0]) print("Usage: %s <ifname> [up|down]" % sys.argv[0])
sys.exit(0) sys.exit(0)
bus = dbus.SystemBus() bus = dbus.SystemBus()
service_name = "org.freedesktop.NetworkManager" service_name = "org.freedesktop.NetworkManager"
proxy = bus.get_object(service_name, "/org/freedesktop/NetworkManager/Settings") proxy = bus.get_object(service_name, "/org/freedesktop/NetworkManager/Settings")
@@ -62,9 +66,11 @@ devpath = nm.GetDeviceByIpIface(iface)
connection_path = None connection_path = None
for path in settings.ListConnections(): for path in settings.ListConnections():
proxy = bus.get_object(service_name, path) 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() config = settings_connection.GetSettings()
if config['connection']['uuid'] == our_uuid: if config["connection"]["uuid"] == our_uuid:
connection_path = path connection_path = path
break break
@@ -84,7 +90,9 @@ if operation == "up":
# Wait for the hotspot to start up # Wait for the hotspot to start up
start = time.time() start = time.time()
while time.time() < start + 10: 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 if state == 2: # NM_ACTIVE_CONNECTION_STATE_ACTIVATED
print("Access point started") print("Access point started")
sys.exit(0) sys.exit(0)
@@ -96,4 +104,3 @@ else:
usage() usage()
sys.exit(0) sys.exit(0)

View File

@@ -14,15 +14,18 @@
# #
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM from gi.repository import GLib, NM
import sys, uuid import sys, uuid
main_loop = None main_loop = None
def print_values(setting, key, value, flags, data): def print_values(setting, key, value, flags, data):
print(" %s.%s: %s" % (setting.get_name(), key, value)) print(" %s.%s: %s" % (setting.get_name(), key, value))
# create an Ethernet connection and return it # create an Ethernet connection and return it
def create_profile(name): def create_profile(name):
profile = NM.SimpleConnection.new() profile = NM.SimpleConnection.new()
@@ -49,6 +52,7 @@ def create_profile(name):
return profile return profile
# callback function # callback function
def added_cb(client, result, data): def added_cb(client, result, data):
try: try:
@@ -58,16 +62,17 @@ def added_cb(client, result, data):
sys.stderr.write("Error: %s\n" % e) sys.stderr.write("Error: %s\n" % e)
main_loop.quit() main_loop.quit()
if __name__ == "__main__": if __name__ == "__main__":
# parse arguments # parse arguments
persistent = False persistent = False
if len(sys.argv) != 2 and len(sys.argv) != 3: 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 len(sys.argv) == 3:
if sys.argv[2] in "persistent" and sys.argv[2][:1] == "p": if sys.argv[2] in "persistent" and sys.argv[2][:1] == "p":
persistent = True persistent = True
else: 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] profile_name = sys.argv[1]
main_loop = GLib.MainLoop() main_loop = GLib.MainLoop()
@@ -82,4 +87,3 @@ if __name__ == "__main__":
client.add_connection_async(con, persistent, None, added_cb, None) client.add_connection_async(con, persistent, None, added_cb, None)
main_loop.run() main_loop.run()

View File

@@ -7,32 +7,52 @@
import sys import sys
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM from gi.repository import GLib, NM
############################################################################### ###############################################################################
def usage(): def usage():
print("Usage: %s [COMMAND [ARG]...]" % sys.argv[0]) print("Usage: %s [COMMAND [ARG]...]" % sys.argv[0])
print("") print("")
print(" COMMANDS: [show]") 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(" destroy PATH|NUMBER")
print(" rollback PATH|NUMBER") print(" rollback PATH|NUMBER")
print(" adjust-rollback-timeout PATH|NUMBER TIMEOUT") print(" adjust-rollback-timeout PATH|NUMBER TIMEOUT")
print("") print("")
sys.exit(1) sys.exit(1)
def show(c, ts = None):
def show(c, ts=None):
cr = c.get_created() cr = c.get_created()
rt = c.get_rollback_timeout() rt = c.get_rollback_timeout()
print("%s:" % c.get_path()) 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: if rt == 0:
print(" timeout: infinity") print(" timeout: infinity")
else: else:
print(" timeout: %u seconds%s" % (rt, "" if ts is None else (" (circa %s sec left)" % ((cr + (rt * 1000) - ts) / 1000.0)))) print(
print(" devices: %s" % (' '.join(sorted(map(lambda x: x.get_iface(), c.get_devices()))))) " 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): def find_checkpoint(client, path):
for c in client.get_checkpoints(): for c in client.get_checkpoints():
@@ -40,6 +60,7 @@ def find_checkpoint(client, path):
return c return c
return None return None
def validate_path(path, client): def validate_path(path, client):
try: try:
num = int(path) num = int(path)
@@ -47,8 +68,8 @@ def validate_path(path, client):
except Exception as e: except Exception as e:
pass pass
if not path or path[0] != '/': if not path or path[0] != "/":
sys.exit('Invalid checkpoint path \"%s\"' % (path)) sys.exit('Invalid checkpoint path "%s"' % (path))
if client is not None: if client is not None:
checkpoint = find_checkpoint(client, path) checkpoint = find_checkpoint(client, path)
@@ -57,6 +78,7 @@ def validate_path(path, client):
return path return path
def do_create(client): def do_create(client):
flags = NM.CheckpointCreateFlags.NONE flags = NM.CheckpointCreateFlags.NONE
if len(sys.argv) < 3: if len(sys.argv) < 3:
@@ -65,13 +87,13 @@ def do_create(client):
timeout = int(sys.argv[2]) timeout = int(sys.argv[2])
devices = [] devices = []
for arg in sys.argv[3:]: for arg in sys.argv[3:]:
if arg == '--destroy-all': if arg == "--destroy-all":
flags |= NM.CheckpointCreateFlags.DESTROY_ALL flags |= NM.CheckpointCreateFlags.DESTROY_ALL
elif arg == '--delete-new-connections': elif arg == "--delete-new-connections":
flags |= NM.CheckpointCreateFlags.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 flags |= NM.CheckpointCreateFlags.DISCONNECT_NEW_DEVICES
elif arg == '--allow-overlapping': elif arg == "--allow-overlapping":
flags |= NM.CheckpointCreateFlags.ALLOW_OVERLAPPING flags |= NM.CheckpointCreateFlags.ALLOW_OVERLAPPING
else: else:
d = client.get_device_by_iface(arg) 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) client.checkpoint_create(devices, timeout, flags, None, create_cb, None)
def do_destroy(client): def do_destroy(client):
if len(sys.argv) < 3: if len(sys.argv) < 3:
sys.exit("Missing checkpoint path") sys.exit("Missing checkpoint path")
@@ -105,6 +128,7 @@ def do_destroy(client):
client.checkpoint_destroy(path, None, destroy_cb, None) client.checkpoint_destroy(path, None, destroy_cb, None)
def do_rollback(client): def do_rollback(client):
if len(sys.argv) < 3: if len(sys.argv) < 3:
sys.exit("Missing checkpoint path") sys.exit("Missing checkpoint path")
@@ -127,6 +151,7 @@ def do_rollback(client):
client.checkpoint_rollback(path, None, rollback_cb, None) client.checkpoint_rollback(path, None, rollback_cb, None)
def do_adjust_rollback_timeout(client): def do_adjust_rollback_timeout(client):
if len(sys.argv) < 3: if len(sys.argv) < 3:
sys.exit("Missing checkpoint path") sys.exit("Missing checkpoint path")
@@ -147,27 +172,31 @@ def do_adjust_rollback_timeout(client):
sys.stderr.write("Failed: %s\n" % e.message) sys.stderr.write("Failed: %s\n" % e.message)
main_loop.quit() 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): def do_show(client):
ts = NM.utils_get_timestamp_msec() ts = NM.utils_get_timestamp_msec()
for c in client.get_checkpoints(): for c in client.get_checkpoints():
show(c, ts) show(c, ts)
if __name__ == '__main__':
if __name__ == "__main__":
nm_client = NM.Client.new(None) nm_client = NM.Client.new(None)
main_loop = GLib.MainLoop() 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) do_show(nm_client)
sys.exit(0) sys.exit(0)
elif sys.argv[1] == 'create': elif sys.argv[1] == "create":
do_create(nm_client) do_create(nm_client)
elif sys.argv[1] == 'destroy': elif sys.argv[1] == "destroy":
do_destroy(nm_client) do_destroy(nm_client)
elif sys.argv[1] == 'rollback': elif sys.argv[1] == "rollback":
do_rollback(nm_client) do_rollback(nm_client)
elif sys.argv[1] == 'adjust-rollback-timeout': elif sys.argv[1] == "adjust-rollback-timeout":
do_adjust_rollback_timeout(nm_client) do_adjust_rollback_timeout(nm_client)
else: else:
usage() usage()

View File

@@ -16,24 +16,25 @@
import sys import sys
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import NM from gi.repository import NM
# supported connection types # supported connection types
connection_types = { connection_types = {
NM.SETTING_VPN_SETTING_NAME, NM.SETTING_VPN_SETTING_NAME,
NM.SETTING_WIRELESS_SETTING_NAME, NM.SETTING_WIRELESS_SETTING_NAME,
NM.SETTING_WIRED_SETTING_NAME, NM.SETTING_WIRED_SETTING_NAME,
NM.SETTING_BOND_SETTING_NAME, NM.SETTING_BOND_SETTING_NAME,
NM.SETTING_BRIDGE_SETTING_NAME, NM.SETTING_BRIDGE_SETTING_NAME,
NM.SETTING_TEAM_SETTING_NAME, NM.SETTING_TEAM_SETTING_NAME,
NM.SETTING_INFINIBAND_SETTING_NAME, NM.SETTING_INFINIBAND_SETTING_NAME,
NM.SETTING_PPPOE_SETTING_NAME, NM.SETTING_PPPOE_SETTING_NAME,
NM.SETTING_ADSL_SETTING_NAME, NM.SETTING_ADSL_SETTING_NAME,
NM.SETTING_BLUETOOTH_SETTING_NAME, NM.SETTING_BLUETOOTH_SETTING_NAME,
NM.SETTING_WIMAX_SETTING_NAME, NM.SETTING_WIMAX_SETTING_NAME,
NM.SETTING_OLPC_MESH_SETTING_NAME, NM.SETTING_OLPC_MESH_SETTING_NAME,
NM.SETTING_GENERIC_SETTING_NAME, NM.SETTING_GENERIC_SETTING_NAME,
} }
@@ -45,9 +46,14 @@ if __name__ == "__main__":
if len(sys.argv) == 2: if len(sys.argv) == 2:
ctype = sys.argv[1] ctype = sys.argv[1]
if ctype not in connection_types: 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: 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 # create Client object
client = NM.Client.new(None) client = NM.Client.new(None)
@@ -63,5 +69,4 @@ if __name__ == "__main__":
client.deactivate_connection(ac, None) client.deactivate_connection(ac, None)
sys.stdout.write("\033[32m -> succeeded\033[0m\n") sys.stdout.write("\033[32m -> succeeded\033[0m\n")
except Exception as e: 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)

View File

@@ -6,7 +6,8 @@
import sys import sys
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM from gi.repository import GLib, NM
# #
@@ -18,6 +19,7 @@ from gi.repository import GLib, NM
main_loop = None main_loop = None
def do_notify(self, property): def do_notify(self, property):
print("notify: %s" % property) print("notify: %s" % property)
ip4cfg = self.get_ip4_config() ip4cfg = self.get_ip4_config()
@@ -25,26 +27,26 @@ def do_notify(self, property):
print("ip4-config: %s" % ip4cfg.get_path()) print("ip4-config: %s" % ip4cfg.get_path())
main_loop.quit() main_loop.quit()
def state_changed(obj, arg1, arg2, arg3): def state_changed(obj, arg1, arg2, arg3):
print("State changed: New: %d, Old: %d, Reason: %d" % (arg1, arg2, arg3)) print("State changed: New: %d, Old: %d, Reason: %d" % (arg1, arg2, arg3))
# Device is connected # Device is connected
if arg1 == 100: if arg1 == 100:
obj.connect('notify::ip4-config', do_notify) obj.connect("notify::ip4-config", do_notify)
if __name__ == "__main__": if __name__ == "__main__":
if len(sys.argv) != 2: 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] dev_iface = sys.argv[1]
c = NM.Client.new(None) c = NM.Client.new(None)
dev = c.get_device_by_iface(dev_iface) dev = c.get_device_by_iface(dev_iface)
if dev is None: 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("Device: %s - %s" % (dev_iface, dev.get_device_type().value_name))
print("---------------------------------------") print("---------------------------------------")
dev.connect('state-changed', state_changed) dev.connect("state-changed", state_changed)
main_loop = GLib.MainLoop() main_loop = GLib.MainLoop()
main_loop.run() main_loop.run()

View File

@@ -5,24 +5,26 @@
# #
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM from gi.repository import GLib, NM
# This example shows how to monitor the DNS configuration # This example shows how to monitor the DNS configuration
main_loop = None main_loop = None
def handle_config(config): def handle_config(config):
print " ---- new configuration ----" print " ---- new configuration ----"
for entry in config: 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() domains = entry.get_domains()
if domains and domains[0]: if domains and domains[0]:
print " domains: %s" % ', '.join(map(str, domains)) print " domains: %s" % ", ".join(map(str, domains))
if entry.get_interface(): if entry.get_interface():
print " interface: %s" % entry.get_interface() print " interface: %s" % entry.get_interface()
print " priority: %d" % entry.get_priority() print " priority: %d" % entry.get_priority()
@@ -31,9 +33,11 @@ def handle_config(config):
print "" print ""
def dns_config_changed(self, property): def dns_config_changed(self, property):
handle_config(self.get_dns_configuration()) handle_config(self.get_dns_configuration())
main_loop = None main_loop = None
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -6,7 +6,8 @@
import sys import sys
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM from gi.repository import GLib, NM
# #
@@ -26,13 +27,15 @@ from gi.repository import GLib, NM
main_loop = None main_loop = None
def connection_saved(connection, error, data): def connection_saved(connection, error, data):
print ("Connection '%s' saved.") % (connection.get_id()) print("Connection '%s' saved.") % (connection.get_id())
main_loop.quit() main_loop.quit()
if __name__ == "__main__": if __name__ == "__main__":
if len(sys.argv) != 2 and len(sys.argv) != 3: 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() main_loop = GLib.MainLoop()
client = NM.Client.new(None) client = NM.Client.new(None)

View File

@@ -7,7 +7,8 @@
# This example lists currently active connections # This example lists currently active connections
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import NM from gi.repository import NM
if __name__ == "__main__": if __name__ == "__main__":
@@ -16,6 +17,4 @@ if __name__ == "__main__":
for ac in acons: for ac in acons:
print("%s (%s) - %s" % (ac.get_id(), ac.get_uuid(), ac.get_connection_type())) print("%s (%s) - %s" % (ac.get_id(), ac.get_uuid(), ac.get_connection_type()))
if len(acons) == 0: if len(acons) == 0:
print("No active connections") print("No active connections")

View File

@@ -7,7 +7,8 @@
# This example lists all devices, both real and placeholder ones # This example lists all devices, both real and placeholder ones
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import NM from gi.repository import NM
if __name__ == "__main__": if __name__ == "__main__":
@@ -18,11 +19,18 @@ if __name__ == "__main__":
print "------------" print "------------"
for d in devices: for d in devices:
if d.is_real(): 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 "\nUnrealized/placeholder devices"
print "------------------------------" print "------------------------------"
for d in devices: for d in devices:
if not d.is_real(): 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(),
)

View File

@@ -5,7 +5,8 @@
# #
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import NM from gi.repository import NM
if __name__ == "__main__": if __name__ == "__main__":
@@ -13,7 +14,10 @@ if __name__ == "__main__":
devices = client.get_devices() devices = client.get_devices()
for d in devices: for d in devices:
print("{:<16} {:<16} {}".format(d.get_iface(), print(
"(" + d.get_type_description() + ")", "{:<16} {:<16} {}".format(
NM.utils_enum_to_str(NM.DeviceInterfaceFlags, d.get_iface(),
d.get_interface_flags()))) "(" + d.get_type_description() + ")",
NM.utils_enum_to_str(NM.DeviceInterfaceFlags, d.get_interface_flags()),
)
)

View File

@@ -6,7 +6,8 @@
import sys import sys
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM from gi.repository import GLib, NM
# This example shows how to get a list of LLDP neighbors for a given interface. # 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 __name__ == "__main__":
if len(sys.argv) != 2: 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] dev_iface = sys.argv[1]
c = NM.Client.new(None) c = NM.Client.new(None)
dev = c.get_device_by_iface(dev_iface) dev = c.get_device_by_iface(dev_iface)
if dev is None: 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() neighbors = dev.get_lldp_neighbors()
for neighbor in neighbors: for neighbor in neighbors:
ret, chassis = neighbor.get_attr_string_value('chassis-id') ret, chassis = neighbor.get_attr_string_value("chassis-id")
ret, port = neighbor.get_attr_string_value('port-id') ret, port = neighbor.get_attr_string_value("port-id")
print "Neighbor: %s - %s" % (chassis, port) print "Neighbor: %s - %s" % (chassis, port)
for attr in neighbor.get_attr_names(): for attr in neighbor.get_attr_names():
attr_type = neighbor.get_attr_type(attr) 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) ret, value = neighbor.get_attr_string_value(attr)
print " %-32s: %s" % (attr, value) 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) ret, value = neighbor.get_attr_uint_value(attr)
print " %-32s: %u" % (attr, value) print " %-32s: %u" % (attr, value)

View File

@@ -6,7 +6,8 @@
import sys, socket import sys, socket
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import NM from gi.repository import NM
# #
@@ -14,11 +15,12 @@ from gi.repository import NM
# from NMIP4Config and NMIP6Config (got out of NMDevice) # from NMIP4Config and NMIP6Config (got out of NMDevice)
# #
def show_addresses(dev, family): def show_addresses(dev, family):
if (family == socket.AF_INET): if family == socket.AF_INET:
ip_cfg = dev.get_ip4_config() ip_cfg = dev.get_ip4_config()
else: else:
ip_cfg = dev.get_ip6_config() ip_cfg = dev.get_ip6_config()
if ip_cfg is None: if ip_cfg is None:
print("None") print("None")
@@ -35,8 +37,9 @@ def show_addresses(dev, family):
print("%s/%d") % (addr, prefix) print("%s/%d") % (addr, prefix)
def show_gateway(dev, family): def show_gateway(dev, family):
if (family == socket.AF_INET): if family == socket.AF_INET:
ip_cfg = dev.get_ip4_config() ip_cfg = dev.get_ip4_config()
else: else:
ip_cfg = dev.get_ip6_config() ip_cfg = dev.get_ip6_config()
@@ -45,16 +48,17 @@ def show_gateway(dev, family):
gw = "None" gw = "None"
else: else:
gw = ip_cfg.get_gateway() gw = ip_cfg.get_gateway()
if gw == '': if gw == "":
gw = "None" gw = "None"
print(gw) print(gw)
def show_routes(dev, family): def show_routes(dev, family):
if (family == socket.AF_INET): if family == socket.AF_INET:
ip_cfg = dev.get_ip4_config() ip_cfg = dev.get_ip4_config()
else: else:
ip_cfg = dev.get_ip6_config() ip_cfg = dev.get_ip6_config()
if ip_cfg is None: if ip_cfg is None:
print("None") print("None")
@@ -75,31 +79,31 @@ def show_routes(dev, family):
def show_dns(dev, family): def show_dns(dev, family):
if (family == socket.AF_INET): if family == socket.AF_INET:
ip_cfg = dev.get_ip4_config() ip_cfg = dev.get_ip4_config()
else: else:
ip_cfg = dev.get_ip6_config() ip_cfg = dev.get_ip6_config()
if ip_cfg is None: if ip_cfg is None:
print("None") print("None")
return return
print ("Nameservers: %s") % (ip_cfg.get_nameservers()) print("Nameservers: %s") % (ip_cfg.get_nameservers())
print ("Domains: %s") % (ip_cfg.get_domains()) print("Domains: %s") % (ip_cfg.get_domains())
print ("Searches: %s") % (ip_cfg.get_searches()) print("Searches: %s") % (ip_cfg.get_searches())
if (family == socket.AF_INET): if family == socket.AF_INET:
print ("WINS: %s") % (ip_cfg.get_wins_servers()) print("WINS: %s") % (ip_cfg.get_wins_servers())
if __name__ == "__main__": if __name__ == "__main__":
if len(sys.argv) != 2: 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] dev_iface = sys.argv[1]
c = NM.Client.new(None) c = NM.Client.new(None)
dev = c.get_device_by_iface(dev_iface) dev = c.get_device_by_iface(dev_iface)
if dev is None: 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("Device: %s - %s" % (dev_iface, dev.get_device_type().value_name))
print("---------------------------------------") print("---------------------------------------")
@@ -142,4 +146,3 @@ if __name__ == "__main__":
print("------------") print("------------")
show_dns(dev, socket.AF_INET6) show_dns(dev, socket.AF_INET6)
print print

View File

@@ -5,14 +5,17 @@
# #
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import NM from gi.repository import NM
# This example asks settings service for all configured connections. # This example asks settings service for all configured connections.
def print_values(setting, key, value, flags, data): def print_values(setting, key, value, flags, data):
print(" %s.%s: %s" % (setting.get_name(), key, value)) print(" %s.%s: %s" % (setting.get_name(), key, value))
if __name__ == "__main__": if __name__ == "__main__":
# create Client object # create Client object
client = NM.Client.new(None) client = NM.Client.new(None)
@@ -25,4 +28,3 @@ if __name__ == "__main__":
print("=== %s : %s ===" % (c.get_id(), c.get_path())) print("=== %s : %s ===" % (c.get_id(), c.get_path()))
c.for_each_setting_value(print_values, None) c.for_each_setting_value(print_values, None)
print("\n") print("\n")

View File

@@ -7,40 +7,47 @@
import sys import sys
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM from gi.repository import GLib, NM
def find_connections(nm_client, arg_type, arg_id): def find_connections(nm_client, arg_type, arg_id):
for c in nm_client.get_connections(): 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 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 yield c
def find_connection_first(nm_client, arg_type, arg_id): def find_connection_first(nm_client, arg_type, arg_id):
for f in find_connections(nm_client, arg_type, arg_id): for f in find_connections(nm_client, arg_type, arg_id):
return f return f
def con_to_str(con): def con_to_str(con):
s_con = con.get_setting_connection() s_con = con.get_setting_connection()
return '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid()) return '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid())
def usage(): def usage():
arg0 = sys.argv[0] arg0 = sys.argv[0]
arg0_spaced = ' ' * len(arg0) arg0_spaced = " " * len(arg0)
print('Usage: %s [ --clone ( [id] <id> | [uuid] <uuid> ) ] \\' % (arg0)) print("Usage: %s [ --clone ( [id] <id> | [uuid] <uuid> ) ] \\" % (arg0))
print(' %s [ --to-disk | --in-memory ] \\' % (arg0_spaced)) print(" %s [ --to-disk | --in-memory ] \\" % (arg0_spaced))
print(' %s [ --block-autoconnect ] \\' % (arg0_spaced)) print(" %s [ --block-autoconnect ] \\" % (arg0_spaced))
print(' %s [ --id <new-id> ] \\' % (arg0_spaced)) print(" %s [ --id <new-id> ] \\" % (arg0_spaced))
print(' %s [ --uuid <new-uuid> ] \\' % (arg0_spaced)) print(" %s [ --uuid <new-uuid> ] \\" % (arg0_spaced))
return 1 return 1
def die(msg, print_usage=False): def die(msg, print_usage=False):
print(msg) print(msg)
if print_usage: if print_usage:
usage() usage()
sys.exit(1) sys.exit(1)
def main(): def main():
main_loop = GLib.MainLoop() main_loop = GLib.MainLoop()
@@ -56,56 +63,62 @@ def main():
argv = list(sys.argv[1:]) argv = list(sys.argv[1:])
while argv: while argv:
if argv[0] == '--clone': if argv[0] == "--clone":
match_type = None match_type = None
if len(argv) < 2: if len(argv) < 2:
die('missing argument for --clone option') die("missing argument for --clone option")
if argv[0] in ['id', 'uuid']: if argv[0] in ["id", "uuid"]:
match_type = argv[0] match_type = argv[0]
if len(argv) < 3: if len(argv) < 3:
die('missing argument for "--clone %s" option' % (match_type)) die('missing argument for "--clone %s" option' % (match_type))
argv = argv[1:] argv = argv[1:]
if cons: 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])) cons.extend(find_connections(nm_client, match_type, argv[1]))
if len(cons) == 0: 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: 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:] argv = argv[2:]
continue continue
if argv[0] in ['--block-autoconnect']: if argv[0] in ["--block-autoconnect"]:
arg_block_autoconnect = NM.SettingsAddConnection2Flags.BLOCK_AUTOCONNECT arg_block_autoconnect = NM.SettingsAddConnection2Flags.BLOCK_AUTOCONNECT
argv = argv[1:] argv = argv[1:]
continue continue
if argv[0] in ['--to-disk', '--in-memory']: if argv[0] in ["--to-disk", "--in-memory"]:
if argv[0] == '--to-disk': if argv[0] == "--to-disk":
v = NM.SettingsAddConnection2Flags.TO_DISK v = NM.SettingsAddConnection2Flags.TO_DISK
elif argv[0] == '--in-memory': elif argv[0] == "--in-memory":
v = NM.SettingsAddConnection2Flags.IN_MEMORY v = NM.SettingsAddConnection2Flags.IN_MEMORY
else: else:
assert(False) assert False
if arg_mode is not None: if arg_mode is not None:
die('duplicate storage modes ("%s")' % (argv[0])) die('duplicate storage modes ("%s")' % (argv[0]))
arg_mode = v arg_mode = v
argv = argv[1:] argv = argv[1:]
continue continue
if argv[0] in ['--id']: if argv[0] in ["--id"]:
if len(argv) < 2: if len(argv) < 2:
die('missing argument for --id option') die("missing argument for --id option")
arg_id = argv[1] arg_id = argv[1]
argv = argv[2:] argv = argv[2:]
continue continue
if argv[0] in ['--uuid']: if argv[0] in ["--uuid"]:
if len(argv) < 2: if len(argv) < 2:
die('missing argument for --uuid option') die("missing argument for --uuid option")
arg_uuid = argv[1] arg_uuid = argv[1]
argv = argv[2:] argv = argv[2:]
continue continue
die('unknown argument "%s"' % (argv[0])) die('unknown argument "%s"' % (argv[0]))
if len(cons) != 1: if len(cons) != 1:
die('missing --clone argument', True) die("missing --clone argument", True)
con = cons[0] con = cons[0]
@@ -117,31 +130,46 @@ def main():
s_con.set_property(NM.SETTING_CONNECTION_UUID, arg_uuid or NM.utils_uuid_generate()) s_con.set_property(NM.SETTING_CONNECTION_UUID, arg_uuid or NM.utils_uuid_generate())
result = {} result = {}
def _add_connection2_cb(cl, async_result, user_data): def _add_connection2_cb(cl, async_result, user_data):
try: try:
c, r = nm_client.add_connection2_finish(async_result) c, r = nm_client.add_connection2_finish(async_result)
except Exception as e: except Exception as e:
result['error'] = e result["error"] = e
else: else:
result['result'] = r result["result"] = r
result['connection'] = c result["connection"] = c
main_loop.quit() main_loop.quit()
nm_client.add_connection2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL), nm_client.add_connection2(
(arg_mode if arg_mode is not None else NM.SettingsAddConnection2Flags.TO_DISK) con2.to_dbus(NM.ConnectionSerializationFlags.ALL),
| arg_block_autoconnect, (arg_mode if arg_mode is not None else NM.SettingsAddConnection2Flags.TO_DISK)
None, | arg_block_autoconnect,
False, None,
None, False,
_add_connection2_cb, None,
None) _add_connection2_cb,
None,
)
main_loop.run() main_loop.run()
if 'error' in result: if "error" in result:
die('update connection %s failed [%s]: %s' % (con_to_str(con2), ' '.join(sys.argv), result['error'])) 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() main()

View File

@@ -11,33 +11,37 @@ import sys
import re import re
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM from gi.repository import GLib, NM
def usage(): def usage():
print('Usage: %s [[id] <id>]' % (sys.argv[0])) print("Usage: %s [[id] <id>]" % (sys.argv[0]))
print(' %s [[uuid] <uuid>]' % (sys.argv[0])) print(" %s [[uuid] <uuid>]" % (sys.argv[0]))
return 1 return 1
def find_connection(nm_client, arg_type, arg_id): def find_connection(nm_client, arg_type, arg_id):
for c in nm_client.get_connections(): 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 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 return c
def main(): def main():
if len(sys.argv) < 2 or len(sys.argv) > 3: if len(sys.argv) < 2 or len(sys.argv) > 3:
return usage() return usage()
if len(sys.argv) == 3: if len(sys.argv) == 3:
arg_type = sys.argv[1] arg_type = sys.argv[1]
arg_id = sys.argv[2] arg_id = sys.argv[2]
if arg_type not in ['id', 'uuid']: if arg_type not in ["id", "uuid"]:
return usage() return usage()
else: else:
arg_type = None arg_type = None
arg_id = sys.argv[1] 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() main_loop = GLib.MainLoop()
@@ -45,57 +49,61 @@ def main():
con = find_connection(nm_client, arg_type, arg_id) con = find_connection(nm_client, arg_type, arg_id)
if con is None: if con is None:
print('could not find a connection %s' % (arg_log)) print("could not find a connection %s" % (arg_log))
return 1 return 1
s_con = con.get_setting_connection() s_con = con.get_setting_connection()
if s_con is None: 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 return 1
arg_log = '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid()) arg_log = '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid())
stable_id = s_con.get_stable_id() stable_id = s_con.get_stable_id()
if not 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 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: if not re_match:
stable_id = stable_id + '-1' stable_id = stable_id + "-1"
else: 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) con2 = NM.SimpleConnection.new_clone(con)
s_con = con2.get_setting_connection() s_con = con2.get_setting_connection()
s_con.set_property(NM.SETTING_CONNECTION_STABLE_ID, stable_id) s_con.set_property(NM.SETTING_CONNECTION_STABLE_ID, stable_id)
result = {} result = {}
def _update2_cb(con, async_result, user_data): def _update2_cb(con, async_result, user_data):
try: try:
r = con.update2_finish(async_result) r = con.update2_finish(async_result)
except Exception as e: except Exception as e:
result['error'] = e result["error"] = e
else: else:
result['result'] = r result["result"] = r
main_loop.quit() main_loop.quit()
con.update2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL), con.update2(
NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT, con2.to_dbus(NM.ConnectionSerializationFlags.ALL),
None, NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT,
None, None,
_update2_cb, None,
None) _update2_cb,
None,
)
main_loop.run() main_loop.run()
if 'error' in result: if "error" in result:
print('update connection %s failed: %s' % (arg_log, result['error'])) print("update connection %s failed: %s" % (arg_log, result["error"]))
return 1 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)) print('set stable-id to "%s"' % (stable_id))
return 0 return 0
if __name__ == '__main__':
if __name__ == "__main__":
sys.exit(main()) sys.exit(main())

View File

@@ -7,40 +7,50 @@
import sys import sys
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM from gi.repository import GLib, NM
def find_connections(nm_client, arg_type, arg_id): def find_connections(nm_client, arg_type, arg_id):
for c in nm_client.get_connections(): 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 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 yield c
def find_connection_first(nm_client, arg_type, arg_id): def find_connection_first(nm_client, arg_type, arg_id):
for f in find_connections(nm_client, arg_type, arg_id): for f in find_connections(nm_client, arg_type, arg_id):
return f return f
def con_to_str(con): def con_to_str(con):
s_con = con.get_setting_connection() s_con = con.get_setting_connection()
return '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid()) return '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid())
def usage(): def usage():
arg0 = sys.argv[0] arg0 = sys.argv[0]
arg0_spaced = ' ' * len(arg0) arg0_spaced = " " * len(arg0)
print('Usage: %s [ [id] <id> | [uuid] <uuid> ] \\' % (arg0)) print("Usage: %s [ [id] <id> | [uuid] <uuid> ] \\" % (arg0))
print(' %s [ --to-disk | --in-memory | --in-memory-detached | --in-memory-only ] \\' % (arg0_spaced)) print(
print(' %s [ --block-autoconnect ] \\' % (arg0_spaced)) " %s [ --to-disk | --in-memory | --in-memory-detached | --in-memory-only ] \\"
print(' %s [ --volatile ] \\' % (arg0_spaced)) % (arg0_spaced)
print(' %s [ --no-reapply ] \\' % (arg0_spaced)) )
print(" %s [ --block-autoconnect ] \\" % (arg0_spaced))
print(" %s [ --volatile ] \\" % (arg0_spaced))
print(" %s [ --no-reapply ] \\" % (arg0_spaced))
return 1 return 1
def die(msg, print_usage=False): def die(msg, print_usage=False):
print(msg) print(msg)
if print_usage: if print_usage:
usage() usage()
sys.exit(1) sys.exit(1)
def main(): def main():
main_loop = GLib.MainLoop() main_loop = GLib.MainLoop()
@@ -56,9 +66,9 @@ def main():
argv = list(sys.argv[1:]) argv = list(sys.argv[1:])
while argv: while argv:
if argv[0] in ['id', 'uuid']: if argv[0] in ["id", "uuid"]:
if cons: if cons:
die('cannot specify multiple connections') die("cannot specify multiple connections")
if len(argv) < 2: if len(argv) < 2:
die('missing argument for "%s" specifier' % (argv[0])) die('missing argument for "%s" specifier' % (argv[0]))
cons.extend(find_connections(nm_client, argv[0], argv[1])) 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])) die('could not find unique connection for "%s %s"' % (argv[0], argv[1]))
argv = argv[2:] argv = argv[2:]
continue continue
if argv[0] in ['--block-autoconnect']: if argv[0] in ["--block-autoconnect"]:
arg_block_autoconnect = NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT arg_block_autoconnect = NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT
argv = argv[1:] argv = argv[1:]
continue continue
if argv[0] in ['--volatile']: if argv[0] in ["--volatile"]:
arg_volatile = NM.SettingsUpdate2Flags.VOLATILE arg_volatile = NM.SettingsUpdate2Flags.VOLATILE
argv = argv[1:] argv = argv[1:]
continue continue
if argv[0] in ['--no-reapply']: if argv[0] in ["--no-reapply"]:
arg_no_reapply = NM.SettingsUpdate2Flags.NO_REAPPLY arg_no_reapply = NM.SettingsUpdate2Flags.NO_REAPPLY
argv = argv[1:] argv = argv[1:]
continue continue
if argv[0] in ['--to-disk', '--in-memory', '--in-memory-detached', '--in-memory-only']: if argv[0] in [
if argv[0] == '--to-disk': "--to-disk",
"--in-memory",
"--in-memory-detached",
"--in-memory-only",
]:
if argv[0] == "--to-disk":
v = NM.SettingsUpdate2Flags.TO_DISK v = NM.SettingsUpdate2Flags.TO_DISK
elif argv[0] == '--in-memory': elif argv[0] == "--in-memory":
v = NM.SettingsUpdate2Flags.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 v = NM.SettingsUpdate2Flags.IN_MEMORY_DETACHED
elif argv[0] == '--in-memory-only': elif argv[0] == "--in-memory-only":
v = NM.SettingsUpdate2Flags.IN_MEMORY_ONLY v = NM.SettingsUpdate2Flags.IN_MEMORY_ONLY
elif argv[0] == '--keep': elif argv[0] == "--keep":
v = NM.SettingsUpdate2Flags.NONE v = NM.SettingsUpdate2Flags.NONE
else: else:
assert(False) assert False
if arg_mode is not None: if arg_mode is not None:
die('duplicate storage modes ("%s")' % (argv[0])) die('duplicate storage modes ("%s")' % (argv[0]))
arg_mode = v arg_mode = v
@@ -102,45 +117,55 @@ def main():
die('unknown argument "%s"' % (argv[0])) die('unknown argument "%s"' % (argv[0]))
cons.extend(find_connections(nm_client, None, argv[0])) cons.extend(find_connections(nm_client, None, argv[0]))
if len(cons) == 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: 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:] argv = argv[1:]
continue continue
if len(cons) != 1: if len(cons) != 1:
die('missing connection argument', True) die("missing connection argument", True)
con = cons[0] con = cons[0]
con2 = NM.SimpleConnection.new_clone(con) con2 = NM.SimpleConnection.new_clone(con)
result = {} result = {}
def _update2_cb(con, async_result, user_data): def _update2_cb(con, async_result, user_data):
try: try:
r = con.update2_finish(async_result) r = con.update2_finish(async_result)
except Exception as e: except Exception as e:
result['error'] = e result["error"] = e
else: else:
result['result'] = r result["result"] = r
main_loop.quit() main_loop.quit()
con.update2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL), con.update2(
(arg_mode if arg_mode is not None else NM.SettingsUpdate2Flags.NONE) con2.to_dbus(NM.ConnectionSerializationFlags.ALL),
| arg_block_autoconnect (arg_mode if arg_mode is not None else NM.SettingsUpdate2Flags.NONE)
| arg_volatile | arg_block_autoconnect
| arg_no_reapply, | arg_volatile
None, | arg_no_reapply,
None, None,
_update2_cb, None,
None) _update2_cb,
None,
)
main_loop.run() main_loop.run()
if 'error' in result: if "error" in result:
die('update connection %s failed [%s]: %s' % (con_to_str(con2), ' '.join(sys.argv), result['error'])) 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() main()

View File

@@ -39,59 +39,60 @@ import sys
import re import re
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import NM from gi.repository import NM
def pr(v): def pr(v):
import pprint import pprint
pprint.pprint(v, indent=4, depth=5, width=60) pprint.pprint(v, indent=4, depth=5, width=60)
def parse_args(): def parse_args():
args = { args = {"set": False, "set-gobject": False, "filter": [], "data": []}
'set': False,
'set-gobject': False,
'filter': [],
'data': []
}
i = 1 i = 1
while i < len(sys.argv): while i < len(sys.argv):
a = sys.argv[i] a = sys.argv[i]
if i == 1: if i == 1:
if a in ['s', 'set']: if a in ["s", "set"]:
args['set'] = True args["set"] = True
i += 1 i += 1
continue continue
elif a in ['g', 'get']: elif a in ["g", "get"]:
args['set'] = False args["set"] = False
i += 1 i += 1
continue continue
if a in ['id', 'uuid']: if a in ["id", "uuid"]:
args['filter'].append((a, sys.argv[i+1])) args["filter"].append((a, sys.argv[i + 1]))
i += 2 i += 2
continue continue
if a in ['--set-gobject']: if a in ["--set-gobject"]:
args['set-gobject'] = True args["set-gobject"] = True
i += 1 i += 1
continue continue
if a == 'data': if a == "data":
i += 1 i += 1
a = sys.argv[i] a = sys.argv[i]
if args['set']: if args["set"]:
if a == '-d': if a == "-d":
args['data'].append((sys.argv[i+1], None)) args["data"].append((sys.argv[i + 1], None))
else: else:
args['data'].append((a, sys.argv[i+1])) args["data"].append((a, sys.argv[i + 1]))
i += 2 i += 2
else: else:
args['data'].append(a) args["data"].append(a)
i += 1 i += 1
return args return args
def connection_to_str(connection): 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): def connections_filter(connections, filter_data):
connections = list(sorted(connections, key=connection_to_str)) connections = list(sorted(connections, key=connection_to_str))
@@ -102,20 +103,21 @@ def connections_filter(connections, filter_data):
# them multiple times. # them multiple times.
l = [] l = []
for f in filter_data: for f in filter_data:
if f[0] == 'id': if f[0] == "id":
for c in connections: for c in connections:
if f[1] == c.get_id(): if f[1] == c.get_id():
l.append(c) l.append(c)
else: else:
assert(f[0] == 'uuid') assert f[0] == "uuid"
for c in connections: for c in connections:
if f[1] == c.get_uuid(): if f[1] == c.get_uuid():
l.append(c) l.append(c)
return l 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) s_u = connection.get_setting(NM.SettingUser)
n = 'none' n = "none"
keys_len = 0 keys_len = 0
keys = [] keys = []
if s_u is not None: 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) keys_len = len(all_keys)
if data: if data:
for d in 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:]) r = re.compile(d[1:])
keys.extend([k for k in all_keys if r.match(k)]) keys.extend([k for k in all_keys if r.match(k)])
else: else:
keys.append (d) keys.append(d)
else: else:
keys.extend(all_keys) keys.extend(all_keys)
n = '%s' % (keys_len) n = "%s" % (keys_len)
print('%s%s [%s]' % (prefix, connection_to_str(connection), n)) print("%s%s [%s]" % (prefix, connection_to_str(connection), n))
dd = { } dd = {}
if s_u is not None: if s_u is not None:
dd = s_u.get_property(NM.SETTING_USER_DATA) dd = s_u.get_property(NM.SETTING_USER_DATA)
for k in keys: for k in keys:
@@ -145,7 +147,7 @@ def print_user_data(connection, data_allow_regex, data, prefix=''):
else: else:
print('%s MISSING: "%s"' % (prefix, k)) print('%s MISSING: "%s"' % (prefix, k))
else: else:
assert(v == dd.get(k, None)) assert v == dd.get(k, None)
print('%s SET: "%s" = "%s"' % (prefix, k, v)) print('%s SET: "%s" = "%s"' % (prefix, k, v))
else: else:
print('%s MISSING: "%s"' % (prefix, k)) print('%s MISSING: "%s"' % (prefix, k))
@@ -155,20 +157,19 @@ def do_get(connections, data):
first_line = True first_line = True
connections = list(connections) connections = list(connections)
if not connections: if not connections:
print('no matching connections (use id|uuid argument)') print("no matching connections (use id|uuid argument)")
sys.exit(1) sys.exit(1)
for c in connections: for c in connections:
if first_line: if first_line:
first_line = False first_line = False
else: else:
print('') print("")
print_user_data(c, True, data) print_user_data(c, True, data)
def do_set(connection, data, set_gobject): def do_set(connection, data, set_gobject):
print_user_data(connection, False, print_user_data(connection, False, [d[0] for d in data], prefix="BEFORE: ")
[d[0] for d in data], print("")
prefix = 'BEFORE: ')
print('')
s_u = connection.get_setting(NM.SettingUser) s_u = connection.get_setting(NM.SettingUser)
if s_u is None: if s_u is None:
connection.add_setting(NM.SettingUser()) 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)) print('error setting key "%s" = "%s": %s' % (key, val, e))
sys.exit(1) sys.exit(1)
try: try:
connection.commit_changes(True, None) connection.commit_changes(True, None)
except Exception as e: except Exception as e:
print('failure to commit connection: %s' % (e)) print("failure to commit connection: %s" % (e))
sys.exit(1) sys.exit(1)
print('') print("")
print_user_data(connection, False, print_user_data(connection, False, [d[0] for d in data], prefix="AFTER: ")
[d[0] for d in data],
prefix = 'AFTER: ')
############################################################################### ###############################################################################
if __name__ == '__main__': if __name__ == "__main__":
args = parse_args() args = parse_args()
nm_client = NM.Client.new(None) 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 args["set"]:
if not args['data']: if not args["data"]:
print('Requires one or more arguments to set or delete') print("Requires one or more arguments to set or delete")
sys.exit(1) sys.exit(1)
if len(connections) != 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])' % print(
(len(connections), ', '.join([connection_to_str(c) for c in connections]))) "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) sys.exit(1)
do_set(connections[0], args['data'], args['set-gobject']) do_set(connections[0], args["data"], args["set-gobject"])
else: else:
do_get(connections, args['data']) do_get(connections, args["data"])

View File

@@ -7,7 +7,8 @@
import locale import locale
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import NM 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/ # an error without it: http://www.python.org/dev/peps/pep-0263/
# #
def clamp(value, minvalue, maxvalue): def clamp(value, minvalue, maxvalue):
return max(minvalue, min(value, maxvalue)) return max(minvalue, min(value, maxvalue))
def ssid_to_utf8(ap): def ssid_to_utf8(ap):
ssid = ap.get_ssid() ssid = ap.get_ssid()
if not ssid: if not ssid:
return "" return ""
return NM.utils_ssid_to_utf8(ap.get_ssid().get_data()) return NM.utils_ssid_to_utf8(ap.get_ssid().get_data())
def print_device_info(device): def print_device_info(device):
active_ap = dev.get_active_access_point() active_ap = dev.get_active_access_point()
ssid = None ssid = None
if active_ap is not None: if active_ap is not None:
ssid = ssid_to_utf8(active_ap) 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(info)
print('=' * len(info)) print("=" * len(info))
def mode_to_string(mode): def mode_to_string(mode):
if mode == getattr(NM, '80211Mode').INFRA: if mode == getattr(NM, "80211Mode").INFRA:
return "INFRA" return "INFRA"
if mode == getattr(NM, '80211Mode').ADHOC: if mode == getattr(NM, "80211Mode").ADHOC:
return "ADHOC" return "ADHOC"
if mode == getattr(NM, '80211Mode').AP: if mode == getattr(NM, "80211Mode").AP:
return "AP" return "AP"
return "UNKNOWN" return "UNKNOWN"
def flags_to_string(flags): def flags_to_string(flags):
if flags & getattr(NM, '80211ApFlags').PRIVACY: if flags & getattr(NM, "80211ApFlags").PRIVACY:
return "PRIVACY" return "PRIVACY"
return "NONE" return "NONE"
def security_flags_to_string(flags): def security_flags_to_string(flags):
NM_AP_FLAGS = getattr(NM, '80211ApSecurityFlags') NM_AP_FLAGS = getattr(NM, "80211ApSecurityFlags")
str = "" str = ""
if flags & NM_AP_FLAGS.PAIR_WEP40: if flags & NM_AP_FLAGS.PAIR_WEP40:
str = str + " PAIR_WEP40" str = str + " PAIR_WEP40"
@@ -79,43 +90,50 @@ def security_flags_to_string(flags):
else: else:
return "NONE" return "NONE"
def flags_to_security(flags, wpa_flags, rsn_flags): def flags_to_security(flags, wpa_flags, rsn_flags):
str = "" str = ""
if ((flags & getattr(NM, '80211ApFlags').PRIVACY) and if (
(wpa_flags == 0) and (rsn_flags == 0)): (flags & getattr(NM, "80211ApFlags").PRIVACY)
str = str + " WEP" and (wpa_flags == 0)
and (rsn_flags == 0)
):
str = str + " WEP"
if wpa_flags != 0: if wpa_flags != 0:
str = str + " WPA1" str = str + " WPA1"
if rsn_flags != 0: if rsn_flags != 0:
str = str + " WPA2" str = str + " WPA2"
if ((wpa_flags & getattr(NM, '80211ApSecurityFlags').KEY_MGMT_802_1X) or if (wpa_flags & getattr(NM, "80211ApSecurityFlags").KEY_MGMT_802_1X) or (
(rsn_flags & getattr(NM, '80211ApSecurityFlags').KEY_MGMT_802_1X)): rsn_flags & getattr(NM, "80211ApSecurityFlags").KEY_MGMT_802_1X
):
str = str + " 802.1X" str = str + " 802.1X"
return str.lstrip() return str.lstrip()
def print_ap_info(ap): def print_ap_info(ap):
strength = ap.get_strength() strength = ap.get_strength()
frequency = ap.get_frequency() frequency = ap.get_frequency()
flags = ap.get_flags() flags = ap.get_flags()
wpa_flags = ap.get_wpa_flags() wpa_flags = ap.get_wpa_flags()
rsn_flags = ap.get_rsn_flags() rsn_flags = ap.get_rsn_flags()
print("SSID: %s" % (ssid_to_utf8(ap))) print("SSID: %s" % (ssid_to_utf8(ap)))
print("BSSID: %s" % (ap.get_bssid())) print("BSSID: %s" % (ap.get_bssid()))
print("Frequency: %s" % (frequency)) print("Frequency: %s" % (frequency))
print("Channel: %s" % (NM.utils_wifi_freq_to_channel(frequency))) print("Channel: %s" % (NM.utils_wifi_freq_to_channel(frequency)))
print("Mode: %s" % (mode_to_string(ap.get_mode()))) print("Mode: %s" % (mode_to_string(ap.get_mode())))
print("Flags: %s" % (flags_to_string(flags))) print("Flags: %s" % (flags_to_string(flags)))
print("WPA flags: %s" % (security_flags_to_string(wpa_flags))) print("WPA flags: %s" % (security_flags_to_string(wpa_flags)))
print("RSN flags: %s" % (security_flags_to_string(rsn_flags))) print("RSN flags: %s" % (security_flags_to_string(rsn_flags)))
print("Security: %s" % (flags_to_security(flags, wpa_flags, 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("Strength: %s %s%%" % (NM.utils_wifi_strength_bars(strength), strength))
print print
if __name__ == "__main__": if __name__ == "__main__":
# Python apparently doesn't call setlocale() on its own? We have to call this or else # 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 # NM.utils_wifi_strength_bars() will think the locale is ASCII-only, and return the
# fallback characters rather than the unicode bars # fallback characters rather than the unicode bars
locale.setlocale(locale.LC_ALL, '') locale.setlocale(locale.LC_ALL, "")
nmc = NM.Client.new(None) nmc = NM.Client.new(None)
devs = nmc.get_devices() devs = nmc.get_devices()
@@ -125,4 +143,3 @@ if __name__ == "__main__":
print_device_info(dev) print_device_info(dev)
for ap in dev.get_access_points(): for ap in dev.get_access_points():
print_ap_info(ap) print_ap_info(ap)

View File

@@ -13,7 +13,8 @@
# #
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM from gi.repository import GLib, NM
import sys, socket import sys, socket
@@ -25,7 +26,9 @@ if __name__ == "__main__":
method = sys.argv[2] method = sys.argv[2]
if (method == "static" or method == "manual") and len(sys.argv) < 5: 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) sys.exit(1)
uuid = sys.argv[1] uuid = sys.argv[1]
@@ -69,4 +72,3 @@ if __name__ == "__main__":
except Exception as e: except Exception as e:
sys.stderr.write("Error: %s\n" % e) sys.stderr.write("Error: %s\n" % e)
break break

View File

@@ -9,7 +9,8 @@
# VPN plugin. # VPN plugin.
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM from gi.repository import GLib, NM
import sys import sys
@@ -35,17 +36,21 @@ for vpn_info in NM.VpnPluginInfo.list_load():
break break
if connection is None: 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) sys.exit(1)
connection.normalize() 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) client = NM.Client.new(None)
main_loop = GLib.MainLoop() main_loop = GLib.MainLoop()
def added_cb(client, result, data): def added_cb(client, result, data):
try: try:
client.add_connection_finish(result) client.add_connection_finish(result)
@@ -54,6 +59,7 @@ def added_cb(client, result, data):
print("ERROR: failed to add connection: %s\n" % e) print("ERROR: failed to add connection: %s\n" % e)
main_loop.quit() main_loop.quit()
client.add_connection_async(connection, True, None, added_cb, None) client.add_connection_async(connection, True, None, added_cb, None)
main_loop.run() main_loop.run()

View File

@@ -9,12 +9,14 @@
import sys import sys
import uuid import uuid
import gi import gi
gi.require_version('NM', '1.0')
gi.require_version("NM", "1.0")
from gi.repository import GLib, NM from gi.repository import GLib, NM
main_loop = None main_loop = None
client = None client = None
def create_profile(name, peer_mac): def create_profile(name, peer_mac):
profile = NM.SimpleConnection.new() profile = NM.SimpleConnection.new()
@@ -32,8 +34,10 @@ def create_profile(name, peer_mac):
s_wifi_p2p = NM.SettingWifiP2P.new() 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_PEER, peer_mac)
s_wifi_p2p.set_property(NM.SETTING_WIFI_P2P_WFD_IES, s_wifi_p2p.set_property(
GLib.Bytes.new(b'\x00\x00\x06\x00\x90\x1c\x44\x00\xc8')) 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_con)
profile.add_setting(s_ip4) profile.add_setting(s_ip4)
@@ -42,6 +46,7 @@ def create_profile(name, peer_mac):
return profile return profile
def activated_cb(client, result, data): def activated_cb(client, result, data):
try: try:
client.add_and_activate_connection2_finish(result) client.add_and_activate_connection2_finish(result)
@@ -50,35 +55,37 @@ def activated_cb(client, result, data):
sys.stderr.write("Error: %s\n" % e) sys.stderr.write("Error: %s\n" % e)
main_loop.quit() main_loop.quit()
def scan_timeout_cb(device): def scan_timeout_cb(device):
peers = device.get_peers() peers = device.get_peers()
if len(peers) == 0: if len(peers) == 0:
main_loop.quit() main_loop.quit()
sys.exit("No peer found") 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: for p in peers:
if p.get_wfd_ies() is not None: if p.get_wfd_ies() is not None:
ies = p.get_wfd_ies().get_data().hex() ies = p.get_wfd_ies().get_data().hex()
else: else:
ies = "" ies = ""
print(" {:20} {:30} {:3} {:30}".format(p.get_hw_address(), print(
p.get_name(), " {:20} {:30} {:3} {:30}".format(
p.get_strength(), p.get_hw_address(), p.get_name(), p.get_strength(), ies
ies)) )
)
print("") print("")
# Connect to first peer # Connect to first peer
profile = create_profile('P2P-connection', peers[0].get_hw_address()) profile = create_profile("P2P-connection", peers[0].get_hw_address())
client.add_and_activate_connection2(profile, client.add_and_activate_connection2(
device, profile, device, "/", GLib.Variant("a{sv}", {}), None, activated_cb, None
"/", )
GLib.Variant('a{sv}', {}), print(
None, " * Connecting to peer {} using profile '{}'".format(
activated_cb, peers[0].get_hw_address(), profile.get_id()
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): def start_find_cb(device, async_result, user_data):
try: try:
@@ -87,9 +94,10 @@ def start_find_cb(device, async_result, user_data):
sys.stderr.write("Error: %s\n" % e) sys.stderr.write("Error: %s\n" % e)
main_loop.quit() 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) GLib.timeout_add(10000, scan_timeout_cb, device)
if __name__ == "__main__": if __name__ == "__main__":
client = NM.Client.new(None) client = NM.Client.new(None)
device = None device = None
@@ -103,7 +111,7 @@ if __name__ == "__main__":
if device is None: if device is None:
sys.exit("No Wi-Fi P2P device found") 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 = GLib.MainLoop()
main_loop.run() main_loop.run()

View File

@@ -6,11 +6,13 @@ import dbus
import dbus.service import dbus.service
import dbus.mainloop.glib import dbus.mainloop.glib
IFACE_SECRET_AGENT = 'org.freedesktop.NetworkManager.SecretAgent' IFACE_SECRET_AGENT = "org.freedesktop.NetworkManager.SecretAgent"
IFACE_AGENT_MANAGER = 'org.freedesktop.NetworkManager.AgentManager' IFACE_AGENT_MANAGER = "org.freedesktop.NetworkManager.AgentManager"
class NotAuthorizedException(dbus.DBusException): class NotAuthorizedException(dbus.DBusException):
_dbus_error_name = IFACE_SECRET_AGENT + '.NotAuthorized' _dbus_error_name = IFACE_SECRET_AGENT + ".NotAuthorized"
class Agent(dbus.service.Object): class Agent(dbus.service.Object):
def __init__(self, bus, object_path): def __init__(self, bus, object_path):
@@ -18,41 +20,58 @@ class Agent(dbus.service.Object):
self.bus = bus self.bus = bus
dbus.service.Object.__init__(self, bus, object_path) dbus.service.Object.__init__(self, bus, object_path)
@dbus.service.method(IFACE_SECRET_AGENT, @dbus.service.method(
in_signature='a{sa{sv}}osasb', IFACE_SECRET_AGENT,
out_signature='a{sa{sv}}', in_signature="a{sa{sv}}osasb",
sender_keyword='sender') out_signature="a{sa{sv}}",
def GetSecrets(self, connection_hash, connection_path, setting_name, hints, request_new, sender=None): sender_keyword="sender",
)
def GetSecrets(
self,
connection_hash,
connection_path,
setting_name,
hints,
request_new,
sender=None,
):
if not sender: if not sender:
raise NotAuthorizedException("Internal error: couldn't get sender") raise NotAuthorizedException("Internal error: couldn't get sender")
uid = self.bus.get_unix_user(sender) uid = self.bus.get_unix_user(sender)
if uid != 0: if uid != 0:
raise NotAuthorizedException("UID %d not authorized" % uid) raise NotAuthorizedException("UID %d not authorized" % uid)
print("Secrets requested path '%s' setting '%s' hints '%s' new %d" % (connection_path, setting_name, str(hints), request_new)) print(
"Secrets requested path '%s' setting '%s' hints '%s' new %d"
% (connection_path, setting_name, str(hints), request_new)
)
# return some random GSM secrets # return some random GSM secrets
s_gsm = dbus.Dictionary({'password': 'asdfadfasdfaf'}) s_gsm = dbus.Dictionary({"password": "asdfadfasdfaf"})
con = dbus.Dictionary({'gsm': s_gsm}) con = dbus.Dictionary({"gsm": s_gsm})
return con return con
def register(proxy): def register(proxy):
proxy.Register("test.agent.id", dbus_interface=IFACE_AGENT_MANAGER) proxy.Register("test.agent.id", dbus_interface=IFACE_AGENT_MANAGER)
print("Registered!") print("Registered!")
return False return False
def unregister(proxy, loop): def unregister(proxy, loop):
proxy.Unregister(dbus_interface=IFACE_AGENT_MANAGER) proxy.Unregister(dbus_interface=IFACE_AGENT_MANAGER)
loop.quit() loop.quit()
return False return False
def main(): def main():
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus() bus = dbus.SystemBus()
obj = Agent(bus, "/org/freedesktop/NetworkManager/SecretAgent") obj = Agent(bus, "/org/freedesktop/NetworkManager/SecretAgent")
proxy = bus.get_object("org.freedesktop.NetworkManager", proxy = bus.get_object(
"/org/freedesktop/NetworkManager/AgentManager") "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/AgentManager"
)
mainloop = GLib.MainLoop() mainloop = GLib.MainLoop()
@@ -65,8 +84,8 @@ def main():
pass pass
print("Unregistering...") print("Unregistering...")
unregister(proxy, mainloop); unregister(proxy, mainloop)
if __name__ == '__main__':
if __name__ == "__main__":
main() main()

View File

@@ -6,56 +6,85 @@ import argparse
bus = dbus.SystemBus() bus = dbus.SystemBus()
parser = argparse.ArgumentParser(description='Interface to easily control logging levels for NetworkManager, ModemManager, and wpasupplicant.') parser = argparse.ArgumentParser(
description="Interface to easily control logging levels for NetworkManager, ModemManager, and wpasupplicant."
)
# NM options # NM options
parser.add_argument('--nm', dest='do_set_nm_logging', action='store', parser.add_argument(
help='modify log level for NetworkManager (debug, info, etc.)') "--nm",
parser.add_argument('--domains', dest='log_domains', action='store', dest="do_set_nm_logging",
default=[], nargs='+', action="store",
help='log "domains" to use with NetworkManager (HW, CORE, etc.)') help="modify log level for NetworkManager (debug, info, etc.)",
)
parser.add_argument(
"--domains",
dest="log_domains",
action="store",
default=[],
nargs="+",
help='log "domains" to use with NetworkManager (HW, CORE, etc.)',
)
# MM options # MM options
parser.add_argument('--mm', dest='do_set_mm_logging', action='store', parser.add_argument(
help='modify log level for ModemManager (debug, info, etc.)') "--mm",
dest="do_set_mm_logging",
action="store",
help="modify log level for ModemManager (debug, info, etc.)",
)
# wpasupplicant options # wpasupplicant options
parser.add_argument('--wpa', dest='do_set_wpa_logging', action='store', parser.add_argument(
help='modify log level for wpasupplicant (debug, msgdump, info, etc.)') "--wpa",
dest="do_set_wpa_logging",
action="store",
help="modify log level for wpasupplicant (debug, msgdump, info, etc.)",
)
args = parser.parse_args() args = parser.parse_args()
if args.do_set_nm_logging: if args.do_set_nm_logging:
#print args.log_domains # print args.log_domains
dom_msg = "" dom_msg = ""
if args.log_domains: if args.log_domains:
dom_msg = " for domains: " + ','.join(args.log_domains) dom_msg = " for domains: " + ",".join(args.log_domains)
print("Setting NetworkManager log level to '" + args.do_set_nm_logging + "'" + dom_msg) print(
"Setting NetworkManager log level to '" + args.do_set_nm_logging + "'" + dom_msg
)
nm_bus = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') nm_bus = bus.get_object(
nm = dbus.Interface(nm_bus, dbus_interface='org.freedesktop.NetworkManager') "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
nm.SetLogging(args.do_set_nm_logging, ','.join(args.log_domains)) )
nm = dbus.Interface(nm_bus, dbus_interface="org.freedesktop.NetworkManager")
nm.SetLogging(args.do_set_nm_logging, ",".join(args.log_domains))
if args.do_set_mm_logging: if args.do_set_mm_logging:
print("Setting ModemManager log level to '" + args.do_set_mm_logging + "'") print("Setting ModemManager log level to '" + args.do_set_mm_logging + "'")
mm_bus = bus.get_object('org.freedesktop.ModemManager', '/org/freedesktop/ModemManager') mm_bus = bus.get_object(
mm = dbus.Interface(mm_bus, dbus_interface='org.freedesktop.ModemManager') "org.freedesktop.ModemManager", "/org/freedesktop/ModemManager"
)
mm = dbus.Interface(mm_bus, dbus_interface="org.freedesktop.ModemManager")
mm.SetLogging(args.do_set_mm_logging) mm.SetLogging(args.do_set_mm_logging)
if args.do_set_wpa_logging: if args.do_set_wpa_logging:
print("Setting wpa_supplicant log level to '" + args.do_set_wpa_logging + "'") print("Setting wpa_supplicant log level to '" + args.do_set_wpa_logging + "'")
if 'debug' in args.do_set_wpa_logging or 'msgdump' in args.do_set_wpa_logging: if "debug" in args.do_set_wpa_logging or "msgdump" in args.do_set_wpa_logging:
print("Enabling timestamps for wpasupplicant debugging logs") print("Enabling timestamps for wpasupplicant debugging logs")
use_timestamps = dbus.Boolean(True, variant_level=1) use_timestamps = dbus.Boolean(True, variant_level=1)
else: else:
print("Disabling timestamps for wpasupplicant debugging logs") print("Disabling timestamps for wpasupplicant debugging logs")
use_timestamps = dbus.Boolean(False, variant_level=1) use_timestamps = dbus.Boolean(False, variant_level=1)
wpa_bus = bus.get_object('fi.w1.wpa_supplicant1', '/fi/w1/wpa_supplicant1') wpa_bus = bus.get_object("fi.w1.wpa_supplicant1", "/fi/w1/wpa_supplicant1")
wpa_properties = dbus.Interface(wpa_bus, dbus_interface='org.freedesktop.DBus.Properties') wpa_properties = dbus.Interface(
wpa_properties.Set('fi.w1.wpa_supplicant1', 'DebugTimestamp', use_timestamps) wpa_bus, dbus_interface="org.freedesktop.DBus.Properties"
wpa_properties.Set('fi.w1.wpa_supplicant1', 'DebugLevel', )
dbus.String(args.do_set_wpa_logging, variant_level=1)) wpa_properties.Set("fi.w1.wpa_supplicant1", "DebugTimestamp", use_timestamps)
wpa_properties.Set(
"fi.w1.wpa_supplicant1",
"DebugLevel",
dbus.String(args.do_set_wpa_logging, variant_level=1),
)

View File

@@ -8,171 +8,196 @@ from __future__ import print_function
import os import os
import gi import gi
gi.require_version('GIRepository', '2.0')
gi.require_version("GIRepository", "2.0")
from gi.repository import GIRepository from gi.repository import GIRepository
import argparse, re, sys import argparse, re, sys
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
try: try:
libs = os.environ['LD_LIBRARY_PATH'].split(':') libs = os.environ["LD_LIBRARY_PATH"].split(":")
libs.reverse() libs.reverse()
for lib in libs: for lib in libs:
GIRepository.Repository.prepend_library_path(lib) GIRepository.Repository.prepend_library_path(lib)
except AttributeError: except AttributeError:
# An old GI version, that has no prepend_library_path # An old GI version, that has no prepend_library_path
# It's alright, it probably interprets LD_LIBRARY_PATH # It's alright, it probably interprets LD_LIBRARY_PATH
# correctly. # correctly.
pass pass
except KeyError: except KeyError:
pass pass
gi.require_version('NM', '1.0') gi.require_version("NM", "1.0")
from gi.repository import NM, GObject from gi.repository import NM, GObject
dbus_type_name_map = { dbus_type_name_map = {
'b': 'boolean', "b": "boolean",
's': 'string', "s": "string",
'i': 'int32', "i": "int32",
'u': 'uint32', "u": "uint32",
't': 'uint64', "t": "uint64",
'x': 'int64', "x": "int64",
'y': 'byte', "y": "byte",
'as': 'array of string', "as": "array of string",
'au': 'array of uint32', "au": "array of uint32",
'ay': 'byte array', "ay": "byte array",
'a{ss}': 'dict of string to string', "a{ss}": "dict of string to string",
'a{sv}': 'vardict', "a{sv}": "vardict",
'aa{sv}': 'array of vardict', "aa{sv}": "array of vardict",
'aau': 'array of array of uint32', "aau": "array of array of uint32",
'aay': 'array of byte array', "aay": "array of byte array",
'a(ayuay)': 'array of legacy IPv6 address struct', "a(ayuay)": "array of legacy IPv6 address struct",
'a(ayuayu)': 'array of legacy IPv6 route struct', "a(ayuayu)": "array of legacy IPv6 route struct",
} }
ns_map = { ns_map = {
'c': 'http://www.gtk.org/introspection/c/1.0', "c": "http://www.gtk.org/introspection/c/1.0",
'gi': 'http://www.gtk.org/introspection/core/1.0', "gi": "http://www.gtk.org/introspection/core/1.0",
'glib': 'http://www.gtk.org/introspection/glib/1.0' "glib": "http://www.gtk.org/introspection/glib/1.0",
} }
identifier_key = '{%s}identifier' % ns_map['c'] identifier_key = "{%s}identifier" % ns_map["c"]
nick_key = '{%s}nick' % ns_map['glib'] nick_key = "{%s}nick" % ns_map["glib"]
symbol_prefix_key = '{%s}symbol-prefix' % ns_map['c'] symbol_prefix_key = "{%s}symbol-prefix" % ns_map["c"]
constants = { constants = {
'TRUE': 'TRUE', "TRUE": "TRUE",
'FALSE': 'FALSE', "FALSE": "FALSE",
'G_MAXUINT32': 'G_MAXUINT32', "G_MAXUINT32": "G_MAXUINT32",
'NULL': 'NULL' } "NULL": "NULL",
}
setting_names = {} setting_names = {}
def get_setting_name_define(setting): def get_setting_name_define(setting):
n = setting.attrib[symbol_prefix_key] n = setting.attrib[symbol_prefix_key]
if n and n.startswith("setting_"): if n and n.startswith("setting_"):
return n[8:].upper() return n[8:].upper()
raise Exception("Unexpected symbol_prefix_key \"%s\"" % (n)) raise Exception('Unexpected symbol_prefix_key "%s"' % (n))
def init_constants(girxml, settings): def init_constants(girxml, settings):
for const in girxml.findall('./gi:namespace/gi:constant', ns_map): for const in girxml.findall("./gi:namespace/gi:constant", ns_map):
cname = const.attrib['{%s}type' % ns_map['c']] cname = const.attrib["{%s}type" % ns_map["c"]]
cvalue = const.attrib['value'] cvalue = const.attrib["value"]
if const.find('./gi:type[@name="utf8"]', ns_map) is not None: if const.find('./gi:type[@name="utf8"]', ns_map) is not None:
cvalue = '"%s"' % cvalue cvalue = '"%s"' % cvalue
constants[cname] = cvalue constants[cname] = cvalue
for enum in girxml.findall('./gi:namespace/gi:enumeration', ns_map): for enum in girxml.findall("./gi:namespace/gi:enumeration", ns_map):
for enumval in enum.findall('./gi:member', ns_map): for enumval in enum.findall("./gi:member", ns_map):
cname = enumval.attrib[identifier_key] cname = enumval.attrib[identifier_key]
cvalue = '%s (%s)' % (cname, enumval.attrib['value']) cvalue = "%s (%s)" % (cname, enumval.attrib["value"])
constants[cname] = cvalue constants[cname] = cvalue
for enum in girxml.findall('./gi:namespace/gi:bitfield', ns_map): for enum in girxml.findall("./gi:namespace/gi:bitfield", ns_map):
for enumval in enum.findall('./gi:member', ns_map): for enumval in enum.findall("./gi:member", ns_map):
cname = enumval.attrib[identifier_key] cname = enumval.attrib[identifier_key]
cvalue = '%s (0x%x)' % (cname, int(enumval.attrib['value'])) cvalue = "%s (0x%x)" % (cname, int(enumval.attrib["value"]))
constants[cname] = cvalue constants[cname] = cvalue
for setting in settings: for setting in settings:
setting_type_name = 'NM' + setting.attrib['name']; setting_type_name = "NM" + setting.attrib["name"]
setting_name_symbol = 'NM_SETTING_' + get_setting_name_define(setting) + '_SETTING_NAME' setting_name_symbol = (
"NM_SETTING_" + get_setting_name_define(setting) + "_SETTING_NAME"
)
if setting_name_symbol in constants: if setting_name_symbol in constants:
setting_name = constants[setting_name_symbol] setting_name = constants[setting_name_symbol]
setting_names[setting_type_name] = setting_name setting_names[setting_type_name] = setting_name
def get_prop_type(setting, pspec): def get_prop_type(setting, pspec):
dbus_type = setting.get_dbus_property_type(pspec.name).dup_string() dbus_type = setting.get_dbus_property_type(pspec.name).dup_string()
prop_type = dbus_type_name_map[dbus_type] prop_type = dbus_type_name_map[dbus_type]
if GObject.type_is_a(pspec.value_type, GObject.TYPE_ENUM) or GObject.type_is_a(pspec.value_type, GObject.TYPE_FLAGS): if GObject.type_is_a(pspec.value_type, GObject.TYPE_ENUM) or GObject.type_is_a(
pspec.value_type, GObject.TYPE_FLAGS
):
prop_type = "%s (%s)" % (pspec.value_type.name, prop_type) prop_type = "%s (%s)" % (pspec.value_type.name, prop_type)
return prop_type return prop_type
def get_docs(propxml): def get_docs(propxml):
doc_xml = propxml.find('gi:doc', ns_map) doc_xml = propxml.find("gi:doc", ns_map)
if doc_xml is None: if doc_xml is None:
return None return None
doc = doc_xml.text doc = doc_xml.text
if 'deprecated' in propxml.attrib: if "deprecated" in propxml.attrib:
doc = doc + ' Deprecated: ' + propxml.attrib['deprecated'] doc = doc + " Deprecated: " + propxml.attrib["deprecated"]
doc = re.sub(r'\n\s*', r' ', doc) doc = re.sub(r"\n\s*", r" ", doc)
# Expand constants # Expand constants
doc = re.sub(r'%([^%]\w*)', lambda match: constants[match.group(1)], doc) doc = re.sub(r"%([^%]\w*)", lambda match: constants[match.group(1)], doc)
# #NMSettingWired:mac-address -> "mac-address" # #NMSettingWired:mac-address -> "mac-address"
doc = re.sub(r'#[A-Za-z0-9_]*:([A-Za-z0-9_-]*)', r'"\1"', doc) doc = re.sub(r"#[A-Za-z0-9_]*:([A-Za-z0-9_-]*)", r'"\1"', doc)
# #NMSettingWired setting -> "802-3-ethernet" setting # #NMSettingWired setting -> "802-3-ethernet" setting
doc = re.sub(r'#([A-Z]\w*) setting', lambda match: setting_names[match.group(1)] + ' setting', doc) doc = re.sub(
r"#([A-Z]\w*) setting",
lambda match: setting_names[match.group(1)] + " setting",
doc,
)
# remaining gtk-doc cleanup # remaining gtk-doc cleanup
doc = doc.replace('%%', '%') doc = doc.replace("%%", "%")
doc = doc.replace('<!-- -->', '') doc = doc.replace("<!-- -->", "")
doc = re.sub(r' Element-.ype:.*', '', doc) doc = re.sub(r" Element-.ype:.*", "", doc)
doc = re.sub(r'#([A-Z]\w*)', r'\1', doc) doc = re.sub(r"#([A-Z]\w*)", r"\1", doc)
# Remove sentences that refer to functions # Remove sentences that refer to functions
doc = re.sub(r'\.\s+[^.]*\w\(\)[^.]*\.', r'.', doc) doc = re.sub(r"\.\s+[^.]*\w\(\)[^.]*\.", r".", doc)
return doc return doc
def get_default_value(setting, pspec, propxml): def get_default_value(setting, pspec, propxml):
default_value = setting.get_property(pspec.name.replace('-', '_')) default_value = setting.get_property(pspec.name.replace("-", "_"))
if default_value is None: if default_value is None:
return default_value return default_value
value_type = get_prop_type(setting, pspec) value_type = get_prop_type(setting, pspec)
if value_type == 'string' and default_value != '' and pspec.name != 'name': if value_type == "string" and default_value != "" and pspec.name != "name":
default_value = '"%s"' % default_value default_value = '"%s"' % default_value
elif value_type == 'boolean': elif value_type == "boolean":
default_value = str(default_value).upper() default_value = str(default_value).upper()
elif value_type == 'byte array': elif value_type == "byte array":
default_value = '[]' default_value = "[]"
elif str(default_value).startswith('<'): elif str(default_value).startswith("<"):
default_value = None default_value = None
elif str(default_value).startswith('['): elif str(default_value).startswith("["):
default_value = None default_value = None
return default_value return default_value
def settings_sort_key(x): def settings_sort_key(x):
x_prefix = x.attrib['{%s}symbol-prefix' % ns_map['c']] x_prefix = x.attrib["{%s}symbol-prefix" % ns_map["c"]]
# always sort NMSettingConnection first # always sort NMSettingConnection first
return (x_prefix != "setting_connection", x_prefix); return (x_prefix != "setting_connection", x_prefix)
def escape(val): def escape(val):
return str(val).replace('"', '&quot;') return str(val).replace('"', "&quot;")
def usage(): def usage():
print("Usage: %s --gir FILE --output FILE" % sys.argv[0]) print("Usage: %s --gir FILE --output FILE" % sys.argv[0])
exit() exit()
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('-l', '--lib-path', metavar='PATH', action='append', help='path to scan for shared libraries') parser.add_argument(
parser.add_argument('-g', '--gir', metavar='FILE', help='NM-1.0.gir file') "-l",
parser.add_argument('-o', '--output', metavar='FILE', help='output file') "--lib-path",
metavar="PATH",
action="append",
help="path to scan for shared libraries",
)
parser.add_argument("-g", "--gir", metavar="FILE", help="NM-1.0.gir file")
parser.add_argument("-o", "--output", metavar="FILE", help="output file")
args = parser.parse_args() args = parser.parse_args()
if args.gir is None or args.output is None: if args.gir is None or args.output is None:
@@ -183,37 +208,50 @@ if args.lib_path:
GIRepository.Repository.prepend_library_path(lib) GIRepository.Repository.prepend_library_path(lib)
girxml = ET.parse(args.gir).getroot() girxml = ET.parse(args.gir).getroot()
outfile = open(args.output, mode='w') outfile = open(args.output, mode="w")
basexml = girxml.find('./gi:namespace/gi:class[@name="Setting"]', ns_map) basexml = girxml.find('./gi:namespace/gi:class[@name="Setting"]', ns_map)
settings = girxml.findall('./gi:namespace/gi:class[@parent="Setting"]', ns_map) settings = girxml.findall('./gi:namespace/gi:class[@parent="Setting"]', ns_map)
# Hack. Need a better way to do this # Hack. Need a better way to do this
ipxml = girxml.find('./gi:namespace/gi:class[@name="SettingIPConfig"]', ns_map) ipxml = girxml.find('./gi:namespace/gi:class[@name="SettingIPConfig"]', ns_map)
settings.extend(girxml.findall('./gi:namespace/gi:class[@parent="SettingIPConfig"]', ns_map)) settings.extend(
girxml.findall('./gi:namespace/gi:class[@parent="SettingIPConfig"]', ns_map)
)
settings = sorted(settings, key=settings_sort_key) settings = sorted(settings, key=settings_sort_key)
init_constants(girxml, settings) init_constants(girxml, settings)
outfile.write("""<?xml version=\"1.0\"?> outfile.write(
"""<?xml version=\"1.0\"?>
<!DOCTYPE nm-setting-docs [ <!DOCTYPE nm-setting-docs [
<!ENTITY quot "&#34;"> <!ENTITY quot "&#34;">
]> ]>
<nm-setting-docs> <nm-setting-docs>
""") """
)
for settingxml in settings: for settingxml in settings:
if 'abstract' in settingxml.attrib: if "abstract" in settingxml.attrib:
continue continue
new_func = NM.__getattr__(settingxml.attrib['name']) new_func = NM.__getattr__(settingxml.attrib["name"])
setting = new_func() setting = new_func()
class_desc = get_docs(settingxml) class_desc = get_docs(settingxml)
if class_desc is None: if class_desc is None:
raise Exception("%s needs a gtk-doc block with one-line description" % setting.props.name) raise Exception(
outfile.write(" <setting name=\"%s\" description=\"%s\" name_upper=\"%s\" >\n" % (setting.props.name, class_desc, get_setting_name_define (settingxml))) "%s needs a gtk-doc block with one-line description" % setting.props.name
)
outfile.write(
' <setting name="%s" description="%s" name_upper="%s" >\n'
% (setting.props.name, class_desc, get_setting_name_define(settingxml))
)
setting_properties = { prop.name: prop for prop in GObject.list_properties(setting) if prop.name != 'name' } setting_properties = {
prop.name: prop
for prop in GObject.list_properties(setting)
if prop.name != "name"
}
for prop in sorted(setting_properties): for prop in sorted(setting_properties):
pspec = setting_properties[prop] pspec = setting_properties[prop]
@@ -228,17 +266,21 @@ for settingxml in settings:
value_desc = get_docs(propxml) value_desc = get_docs(propxml)
default_value = get_default_value(setting, pspec, propxml) default_value = get_default_value(setting, pspec, propxml)
prop_upper = prop.upper().replace('-', '_') prop_upper = prop.upper().replace("-", "_")
if value_desc is None: if value_desc is None:
raise Exception("%s.%s needs a documentation description" % (setting.props.name, prop)) raise Exception(
"%s.%s needs a documentation description" % (setting.props.name, prop)
)
default_value_as_xml = '' default_value_as_xml = ""
if default_value is not None: if default_value is not None:
default_value_as_xml = (' default=\"%s\"' % (escape(default_value))) default_value_as_xml = ' default="%s"' % (escape(default_value))
outfile.write(" <property name=\"%s\" name_upper=\"%s\" type=\"%s\"%s description=\"%s\" />\n" % outfile.write(
(prop, prop_upper, value_type, default_value_as_xml, escape(value_desc))) ' <property name="%s" name_upper="%s" type="%s"%s description="%s" />\n'
% (prop, prop_upper, value_type, default_value_as_xml, escape(value_desc))
)
outfile.write(" </setting>\n") outfile.write(" </setting>\n")

View File

@@ -61,28 +61,33 @@ _setting_name_order = [
"wpan", "wpan",
] ]
def _setting_name_order_idx(name): def _setting_name_order_idx(name):
try: try:
return _setting_name_order.index(name) return _setting_name_order.index(name)
except ValueError: except ValueError:
return len(_setting_name_order) return len(_setting_name_order)
def key_fcn_setting_name(n1): def key_fcn_setting_name(n1):
return (_setting_name_order_idx(n1), n1) return (_setting_name_order_idx(n1), n1)
def iter_keys_of_dicts(dicts, key = None):
def iter_keys_of_dicts(dicts, key=None):
keys = set([k for d in dicts for k in d.keys()]) keys = set([k for d in dicts for k in d.keys()])
return sorted(keys, key = key) return sorted(keys, key=key)
def node_to_dict(node, tag, key_attr): def node_to_dict(node, tag, key_attr):
dictionary = collections.OrderedDict() dictionary = collections.OrderedDict()
if node is not None: if node is not None:
for n in node.iter(tag): for n in node.iter(tag):
k = n.get(key_attr) k = n.get(key_attr)
assert(k is not None) assert k is not None
dictionary[k] = n dictionary[k] = n
return dictionary return dictionary
def node_get_attr(nodes, name): def node_get_attr(nodes, name):
for n in nodes: for n in nodes:
if n is None: if n is None:
@@ -92,18 +97,20 @@ def node_get_attr(nodes, name):
return x return x
return None return None
def node_set_attr(dst_node, name, nodes): def node_set_attr(dst_node, name, nodes):
x = node_get_attr(nodes, name) x = node_get_attr(nodes, name)
if x: if x:
dst_node.set(name, x) dst_node.set(name, x)
############################################################################### ###############################################################################
gl_only_from_first = False gl_only_from_first = False
argv = list(sys.argv[1:]) argv = list(sys.argv[1:])
while True: while True:
if argv[0] == '--only-from-first': if argv[0] == "--only-from-first":
gl_only_from_first = True gl_only_from_first = True
del argv[0] del argv[0]
continue continue
@@ -119,54 +126,51 @@ gl_input_files = list(argv[1:])
xml_roots = list([ET.parse(f).getroot() for f in gl_input_files]) xml_roots = list([ET.parse(f).getroot() for f in gl_input_files])
assert(all([root.tag == 'nm-setting-docs' for root in xml_roots])) assert all([root.tag == "nm-setting-docs" for root in xml_roots])
settings_roots = list([node_to_dict(root, 'setting', 'name') for root in xml_roots]) settings_roots = list([node_to_dict(root, "setting", "name") for root in xml_roots])
root_node = ET.Element('nm-setting-docs') root_node = ET.Element("nm-setting-docs")
for setting_name in iter_keys_of_dicts(settings_roots, key_fcn_setting_name): for setting_name in iter_keys_of_dicts(settings_roots, key_fcn_setting_name):
settings = list([d.get(setting_name) for d in settings_roots]) settings = list([d.get(setting_name) for d in settings_roots])
if gl_only_from_first \ if gl_only_from_first and settings[0] is None:
and settings[0] is None:
continue continue
properties = list([node_to_dict(s, 'property', 'name') for s in settings]) properties = list([node_to_dict(s, "property", "name") for s in settings])
if gl_only_from_first \ if gl_only_from_first and not properties[0]:
and not properties[0]:
continue continue
setting_node = ET.SubElement(root_node, 'setting') setting_node = ET.SubElement(root_node, "setting")
setting_node.set('name', setting_name) setting_node.set("name", setting_name)
node_set_attr(setting_node, 'description', settings) node_set_attr(setting_node, "description", settings)
node_set_attr(setting_node, 'name_upper', settings) node_set_attr(setting_node, "name_upper", settings)
node_set_attr(setting_node, 'alias', settings) node_set_attr(setting_node, "alias", settings)
for property_name in iter_keys_of_dicts(properties): for property_name in iter_keys_of_dicts(properties):
properties_attrs = list([p.get(property_name) for p in properties]) properties_attrs = list([p.get(property_name) for p in properties])
if gl_only_from_first \ if gl_only_from_first and properties_attrs[0] is None:
and properties_attrs[0] is None:
continue continue
property_node = ET.SubElement(setting_node, 'property') property_node = ET.SubElement(setting_node, "property")
property_node.set('name', property_name) property_node.set("name", property_name)
property_node.set('name_upper', property_name.upper().replace('-', '_')) property_node.set("name_upper", property_name.upper().replace("-", "_"))
x = node_get_attr(properties_attrs, 'format') x = node_get_attr(properties_attrs, "format")
if x: if x:
property_node.set('type', x) property_node.set("type", x)
else: else:
node_set_attr(property_node, 'type', properties_attrs) node_set_attr(property_node, "type", properties_attrs)
node_set_attr(property_node, 'default', properties_attrs) node_set_attr(property_node, "default", properties_attrs)
node_set_attr(property_node, 'description', properties_attrs) node_set_attr(property_node, "description", properties_attrs)
node_set_attr(property_node, 'alias', properties_attrs) node_set_attr(property_node, "alias", properties_attrs)
ET.ElementTree(root_node).write(gl_output_xml_file) ET.ElementTree(root_node).write(gl_output_xml_file)

File diff suppressed because it is too large Load Diff