all: reformat python files with python black
Part of !537. https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/merge_requests/537
This commit is contained in:

committed by
Thomas Haller

parent
b6febb0fd0
commit
be822b52e6
File diff suppressed because it is too large
Load Diff
@@ -20,34 +20,40 @@ import socket, struct, dbus, uuid
|
||||
def ip_to_int(ip_string):
|
||||
return struct.unpack("=I", socket.inet_aton(ip_string))[0]
|
||||
|
||||
|
||||
def int_to_ip(ip_int):
|
||||
return socket.inet_ntoa(struct.pack("=I", ip_int))
|
||||
|
||||
s_wired = dbus.Dictionary({'duplex': 'full'})
|
||||
s_con = dbus.Dictionary({
|
||||
'type': '802-3-ethernet',
|
||||
'uuid': str(uuid.uuid4()),
|
||||
'id': 'MyConnectionExample'})
|
||||
|
||||
addr1 = dbus.Array([ip_to_int("10.1.2.3"), dbus.UInt32(8), ip_to_int("10.1.2.1")], signature=dbus.Signature('u'))
|
||||
s_ip4 = dbus.Dictionary({
|
||||
'addresses': dbus.Array([addr1], signature=dbus.Signature('au')),
|
||||
'method': 'manual'})
|
||||
s_wired = dbus.Dictionary({"duplex": "full"})
|
||||
s_con = dbus.Dictionary(
|
||||
{"type": "802-3-ethernet", "uuid": str(uuid.uuid4()), "id": "MyConnectionExample"}
|
||||
)
|
||||
|
||||
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({
|
||||
'802-3-ethernet': s_wired,
|
||||
'connection': s_con,
|
||||
'ipv4': s_ip4,
|
||||
'ipv6': s_ip6})
|
||||
s_ip6 = dbus.Dictionary({"method": "ignore"})
|
||||
|
||||
con = dbus.Dictionary(
|
||||
{"802-3-ethernet": s_wired, "connection": s_con, "ipv4": s_ip4, "ipv6": s_ip6}
|
||||
)
|
||||
|
||||
|
||||
print("Creating connection:", s_con['id'], "-", s_con['uuid'])
|
||||
print("Creating connection:", s_con["id"], "-", s_con["uuid"])
|
||||
|
||||
bus = dbus.SystemBus()
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings"
|
||||
)
|
||||
settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
|
||||
|
||||
settings.AddConnection(con)
|
||||
|
||||
|
@@ -17,34 +17,33 @@
|
||||
|
||||
import dbus, uuid
|
||||
|
||||
s_wired = dbus.Dictionary({'duplex': 'full'})
|
||||
s_con = dbus.Dictionary({
|
||||
'type': '802-3-ethernet',
|
||||
'uuid': str(uuid.uuid4()),
|
||||
'id': 'MyConnectionExample'})
|
||||
s_wired = dbus.Dictionary({"duplex": "full"})
|
||||
s_con = dbus.Dictionary(
|
||||
{"type": "802-3-ethernet", "uuid": str(uuid.uuid4()), "id": "MyConnectionExample"}
|
||||
)
|
||||
|
||||
addr1 = dbus.Dictionary({
|
||||
'address': '10.1.2.3',
|
||||
'prefix': dbus.UInt32(8)})
|
||||
s_ip4 = dbus.Dictionary({
|
||||
'address-data': dbus.Array([addr1], signature=dbus.Signature('a{sv}')),
|
||||
'gateway': '10.1.2.1',
|
||||
'method': 'manual'})
|
||||
addr1 = dbus.Dictionary({"address": "10.1.2.3", "prefix": dbus.UInt32(8)})
|
||||
s_ip4 = dbus.Dictionary(
|
||||
{
|
||||
"address-data": dbus.Array([addr1], signature=dbus.Signature("a{sv}")),
|
||||
"gateway": "10.1.2.1",
|
||||
"method": "manual",
|
||||
}
|
||||
)
|
||||
|
||||
s_ip6 = dbus.Dictionary({'method': 'ignore'})
|
||||
s_ip6 = dbus.Dictionary({"method": "ignore"})
|
||||
|
||||
con = dbus.Dictionary({
|
||||
'802-3-ethernet': s_wired,
|
||||
'connection': s_con,
|
||||
'ipv4': s_ip4,
|
||||
'ipv6': s_ip6})
|
||||
con = dbus.Dictionary(
|
||||
{"802-3-ethernet": s_wired, "connection": s_con, "ipv4": s_ip4, "ipv6": s_ip6}
|
||||
)
|
||||
|
||||
|
||||
print("Creating connection:", s_con['id'], "-", s_con['uuid'])
|
||||
print("Creating connection:", s_con["id"], "-", s_con["uuid"])
|
||||
|
||||
bus = dbus.SystemBus()
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings"
|
||||
)
|
||||
settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
|
||||
|
||||
settings.AddConnection(con)
|
||||
|
||||
|
@@ -6,45 +6,57 @@
|
||||
|
||||
import dbus, uuid
|
||||
|
||||
|
||||
def path_to_value(path):
|
||||
return dbus.ByteArray("file://".encode("utf-8") + path.encode("utf-8") + "\0".encode("utf-8"))
|
||||
return dbus.ByteArray(
|
||||
"file://".encode("utf-8") + path.encode("utf-8") + "\0".encode("utf-8")
|
||||
)
|
||||
|
||||
s_con = dbus.Dictionary({
|
||||
'type': '802-11-wireless',
|
||||
'uuid': str(uuid.uuid4()),
|
||||
'id': 'My Wifi'})
|
||||
|
||||
s_wifi = dbus.Dictionary({
|
||||
'ssid': dbus.ByteArray("homewifi".encode("utf-8")),
|
||||
'security': '802-11-wireless-security'})
|
||||
s_con = dbus.Dictionary(
|
||||
{"type": "802-11-wireless", "uuid": str(uuid.uuid4()), "id": "My Wifi"}
|
||||
)
|
||||
|
||||
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({
|
||||
'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_wsec = dbus.Dictionary({"key-mgmt": "wpa-eap"})
|
||||
|
||||
s_ip4 = dbus.Dictionary({'method': 'auto'})
|
||||
s_ip6 = dbus.Dictionary({'method': 'ignore'})
|
||||
s_8021x = dbus.Dictionary(
|
||||
{
|
||||
"eap": ["tls"],
|
||||
"identity": "Bill Smith",
|
||||
"client-cert": path_to_value("/some/place/client.pem"),
|
||||
"ca-cert": path_to_value("/some/place/ca-cert.pem"),
|
||||
"private-key": path_to_value("/some/place/privkey.pem"),
|
||||
"private-key-password": "12345testing",
|
||||
}
|
||||
)
|
||||
|
||||
con = dbus.Dictionary({
|
||||
'connection': s_con,
|
||||
'802-11-wireless': s_wifi,
|
||||
'802-11-wireless-security': s_wsec,
|
||||
'802-1x': s_8021x,
|
||||
'ipv4': s_ip4,
|
||||
'ipv6': s_ip6
|
||||
})
|
||||
s_ip4 = dbus.Dictionary({"method": "auto"})
|
||||
s_ip6 = dbus.Dictionary({"method": "ignore"})
|
||||
|
||||
con = dbus.Dictionary(
|
||||
{
|
||||
"connection": s_con,
|
||||
"802-11-wireless": s_wifi,
|
||||
"802-11-wireless-security": s_wsec,
|
||||
"802-1x": s_8021x,
|
||||
"ipv4": s_ip4,
|
||||
"ipv6": s_ip6,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
bus = dbus.SystemBus()
|
||||
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings"
|
||||
)
|
||||
settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
|
||||
|
||||
settings.AddConnection(con)
|
||||
|
||||
|
@@ -6,38 +6,37 @@
|
||||
|
||||
import dbus, uuid
|
||||
|
||||
s_con = dbus.Dictionary({
|
||||
'type': '802-11-wireless',
|
||||
'uuid': str(uuid.uuid4()),
|
||||
'id': 'My-WPA-PSK'})
|
||||
s_con = dbus.Dictionary(
|
||||
{"type": "802-11-wireless", "uuid": str(uuid.uuid4()), "id": "My-WPA-PSK"}
|
||||
)
|
||||
|
||||
s_wifi = dbus.Dictionary({
|
||||
'ssid': dbus.ByteArray("best-wifi".encode("utf-8")),
|
||||
'mode': 'infrastructure',
|
||||
})
|
||||
s_wifi = dbus.Dictionary(
|
||||
{"ssid": dbus.ByteArray("best-wifi".encode("utf-8")), "mode": "infrastructure",}
|
||||
)
|
||||
|
||||
s_wsec = dbus.Dictionary({
|
||||
'key-mgmt': 'wpa-psk',
|
||||
'auth-alg': 'open',
|
||||
'psk': 'super-secret-password',
|
||||
})
|
||||
s_wsec = dbus.Dictionary(
|
||||
{"key-mgmt": "wpa-psk", "auth-alg": "open", "psk": "super-secret-password",}
|
||||
)
|
||||
|
||||
s_ip4 = dbus.Dictionary({'method': 'auto'})
|
||||
s_ip6 = dbus.Dictionary({'method': 'ignore'})
|
||||
s_ip4 = dbus.Dictionary({"method": "auto"})
|
||||
s_ip6 = dbus.Dictionary({"method": "ignore"})
|
||||
|
||||
con = dbus.Dictionary({
|
||||
'connection': s_con,
|
||||
'802-11-wireless': s_wifi,
|
||||
'802-11-wireless-security': s_wsec,
|
||||
'ipv4': s_ip4,
|
||||
'ipv6': s_ip6
|
||||
})
|
||||
con = dbus.Dictionary(
|
||||
{
|
||||
"connection": s_con,
|
||||
"802-11-wireless": s_wifi,
|
||||
"802-11-wireless-security": s_wsec,
|
||||
"ipv4": s_ip4,
|
||||
"ipv6": s_ip6,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
bus = dbus.SystemBus()
|
||||
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings"
|
||||
)
|
||||
settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
|
||||
|
||||
settings.AddConnection(con)
|
||||
|
||||
|
@@ -12,14 +12,18 @@ import dbus, sys
|
||||
|
||||
# Get a proxy for the base NetworkManager object
|
||||
bus = dbus.SystemBus()
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
|
||||
)
|
||||
manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
|
||||
allDevs = manager.GetDevices()
|
||||
|
||||
|
||||
def Usage():
|
||||
print "Usage: %s <ROLLBACK-INTERVAL> [INTERFACE]..." % sys.argv[0]
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def GetDevicePath(ifname):
|
||||
for dev in allDevs:
|
||||
dev_proxy = bus.get_object("org.freedesktop.NetworkManager", dev)
|
||||
@@ -29,6 +33,7 @@ def GetDevicePath(ifname):
|
||||
return dev
|
||||
return
|
||||
|
||||
|
||||
if len(sys.argv) < 2:
|
||||
Usage()
|
||||
|
||||
@@ -46,12 +51,11 @@ for arg in sys.argv[2:]:
|
||||
else:
|
||||
devList.append(path)
|
||||
|
||||
checkpoint = manager.CheckpointCreate(devList,
|
||||
interval,
|
||||
1); # DESTROY_ALL
|
||||
checkpoint = manager.CheckpointCreate(devList, interval, 1)
|
||||
# DESTROY_ALL
|
||||
|
||||
choice = raw_input('Do you want to rollback [y/n]? ').lower()
|
||||
if choice == 'y':
|
||||
choice = raw_input("Do you want to rollback [y/n]? ").lower()
|
||||
if choice == "y":
|
||||
print "Rollback checkpoint"
|
||||
results = manager.CheckpointRollback(checkpoint)
|
||||
for d in results:
|
||||
|
@@ -17,51 +17,59 @@ from gi.repository import GObject
|
||||
|
||||
DBusGMainLoop(set_as_default=True)
|
||||
|
||||
|
||||
def add_connection(con):
|
||||
bus = dbus.SystemBus()
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings"
|
||||
)
|
||||
settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
|
||||
return settings.AddConnection(con)
|
||||
|
||||
def create_bond(bond_name):
|
||||
bond_opts = dbus.Dictionary({'mode': '4'})
|
||||
s_bond = dbus.Dictionary({'options': bond_opts})
|
||||
s_con = dbus.Dictionary({
|
||||
'type': 'bond',
|
||||
'uuid': str(uuid.uuid4()),
|
||||
'id': bond_name,
|
||||
'interface-name': bond_name,
|
||||
'autoconnect': False,
|
||||
'autoconnect-slaves': 1})
|
||||
s_ip4 = dbus.Dictionary({'method': 'auto'})
|
||||
s_ip6 = dbus.Dictionary({'method': 'ignore'})
|
||||
|
||||
con = dbus.Dictionary({
|
||||
'bond': s_bond,
|
||||
'connection': s_con,
|
||||
'ipv4': s_ip4,
|
||||
'ipv6': s_ip6})
|
||||
def create_bond(bond_name):
|
||||
bond_opts = dbus.Dictionary({"mode": "4"})
|
||||
s_bond = dbus.Dictionary({"options": bond_opts})
|
||||
s_con = dbus.Dictionary(
|
||||
{
|
||||
"type": "bond",
|
||||
"uuid": str(uuid.uuid4()),
|
||||
"id": bond_name,
|
||||
"interface-name": bond_name,
|
||||
"autoconnect": False,
|
||||
"autoconnect-slaves": 1,
|
||||
}
|
||||
)
|
||||
s_ip4 = dbus.Dictionary({"method": "auto"})
|
||||
s_ip6 = dbus.Dictionary({"method": "ignore"})
|
||||
|
||||
con = dbus.Dictionary(
|
||||
{"bond": s_bond, "connection": s_con, "ipv4": s_ip4, "ipv6": s_ip6}
|
||||
)
|
||||
print("Creating bond connection: %s" % bond_name)
|
||||
return add_connection(con)
|
||||
|
||||
def create_slave(device, master):
|
||||
slave_name = 'bond-' + master + '-slave-' + device
|
||||
s_wired = dbus.Dictionary({'duplex': 'full'})
|
||||
s_con = dbus.Dictionary({
|
||||
'type': '802-3-ethernet',
|
||||
'uuid': str(uuid.uuid4()),
|
||||
'id': slave_name,
|
||||
'interface-name': device,
|
||||
'autoconnect': False,
|
||||
'master': master,
|
||||
'slave-type': 'bond'})
|
||||
|
||||
con = dbus.Dictionary({
|
||||
'802-3-ethernet': s_wired,
|
||||
'connection': s_con})
|
||||
def create_slave(device, master):
|
||||
slave_name = "bond-" + master + "-slave-" + device
|
||||
s_wired = dbus.Dictionary({"duplex": "full"})
|
||||
s_con = dbus.Dictionary(
|
||||
{
|
||||
"type": "802-3-ethernet",
|
||||
"uuid": str(uuid.uuid4()),
|
||||
"id": slave_name,
|
||||
"interface-name": device,
|
||||
"autoconnect": False,
|
||||
"master": master,
|
||||
"slave-type": "bond",
|
||||
}
|
||||
)
|
||||
|
||||
con = dbus.Dictionary({"802-3-ethernet": s_wired, "connection": s_con})
|
||||
print("Creating slave connection: %s" % slave_name)
|
||||
add_connection(con)
|
||||
|
||||
|
||||
def usage():
|
||||
print("Usage: %s <bond_name> <ifname1> ..." % sys.argv[0])
|
||||
sys.exit(0)
|
||||
@@ -78,22 +86,27 @@ for ifname in sys.argv[2:]:
|
||||
|
||||
# Activate the bond
|
||||
bus = dbus.SystemBus()
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
|
||||
)
|
||||
manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
|
||||
ac = manager.ActivateConnection(bond_path, "/", "/")
|
||||
print("Activating bond: %s (%s)" % (bond_name, ac))
|
||||
|
||||
# Monitor the active bond connection
|
||||
loop = GObject.MainLoop()
|
||||
|
||||
|
||||
def properties_changed(props):
|
||||
if 'State' in props:
|
||||
if props['State'] == 2:
|
||||
if "State" in props:
|
||||
if props["State"] == 2:
|
||||
print("Successfully connected")
|
||||
loop.quit()
|
||||
if props['State'] == 3 or props['State'] == 4:
|
||||
if props["State"] == 3 or props["State"] == 4:
|
||||
print("Bond activation failed")
|
||||
loop.quit()
|
||||
|
||||
|
||||
obj = bus.get_object("org.freedesktop.NetworkManager", ac)
|
||||
iface = dbus.Interface(obj, "org.freedesktop.NetworkManager.Connection.Active")
|
||||
iface.connect_to_signal("PropertiesChanged", properties_changed)
|
||||
|
@@ -16,7 +16,9 @@ if len(sys.argv) != 2:
|
||||
bus = dbus.SystemBus()
|
||||
|
||||
# Get a proxy for the base NetworkManager object
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
|
||||
)
|
||||
manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
|
||||
|
||||
dpath = None
|
||||
@@ -45,4 +47,3 @@ if state <= 3:
|
||||
|
||||
# Tell NM to disconnect it
|
||||
dev_iface.Disconnect()
|
||||
|
||||
|
@@ -13,11 +13,15 @@ import dbus
|
||||
bus = dbus.SystemBus()
|
||||
|
||||
# Get a proxy for the base NetworkManager object
|
||||
m_proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
|
||||
m_proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
|
||||
)
|
||||
manager = dbus.Interface(m_proxy, "org.freedesktop.NetworkManager")
|
||||
mgr_props = dbus.Interface(m_proxy, "org.freedesktop.DBus.Properties")
|
||||
|
||||
s_proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings")
|
||||
s_proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings"
|
||||
)
|
||||
settings = dbus.Interface(s_proxy, "org.freedesktop.NetworkManager.Settings")
|
||||
|
||||
# Find the device the user wants to disconnect
|
||||
@@ -31,12 +35,18 @@ for a in active:
|
||||
uuid = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Uuid")
|
||||
|
||||
# Grab the connection object path so we can get all the connection's settings
|
||||
connection_path = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection")
|
||||
connection_path = a_props.Get(
|
||||
"org.freedesktop.NetworkManager.Connection.Active", "Connection"
|
||||
)
|
||||
c_proxy = bus.get_object("org.freedesktop.NetworkManager", connection_path)
|
||||
connection = dbus.Interface(c_proxy, "org.freedesktop.NetworkManager.Settings.Connection")
|
||||
connection = dbus.Interface(
|
||||
c_proxy, "org.freedesktop.NetworkManager.Settings.Connection"
|
||||
)
|
||||
settings = connection.GetSettings()
|
||||
print("%s (%s) - %s" % (settings['connection']['id'], uuid, settings['connection']['type']))
|
||||
print(
|
||||
"%s (%s) - %s"
|
||||
% (settings["connection"]["id"], uuid, settings["connection"]["type"])
|
||||
)
|
||||
|
||||
if len(active) == 0:
|
||||
print("No active connections")
|
||||
|
||||
|
@@ -30,8 +30,9 @@ proxy = bus.get_object(NM_SERVICE_NAME, "/org/freedesktop/NetworkManager")
|
||||
manager = dbus.Interface(proxy, NM_MANAGER_IFACE)
|
||||
props = dbus.Interface(proxy, DBUS_PROPS_IFACE)
|
||||
|
||||
|
||||
def found_connection_type(ctype):
|
||||
if ctype == '':
|
||||
if ctype == "":
|
||||
print("No active connection")
|
||||
elif ctype in ["gsm", "cdma", "bluetooth"]:
|
||||
print("WWAN is default")
|
||||
@@ -39,6 +40,7 @@ def found_connection_type(ctype):
|
||||
print("WWAN is not default")
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
# Shortcut #1, for NM 1.0
|
||||
try:
|
||||
ctype = props.Get(NM_MANAGER_IFACE, "PrimaryConnectionType")
|
||||
@@ -50,7 +52,7 @@ except KeyError:
|
||||
try:
|
||||
primary = props.Get(NM_MANAGER_IFACE, "PrimaryConnection")
|
||||
if not primary:
|
||||
found_connection_type('')
|
||||
found_connection_type("")
|
||||
primary_proxy = bus.get_object(NM_SERVICE_NAME, primary)
|
||||
primary_props = dbus.Interface(primary_proxy, DBUS_PROPS_IFACE)
|
||||
ctype = primary_props.Get(NM_ACTIVE_CONNECTION_INTERFACE, "Type")
|
||||
@@ -83,4 +85,3 @@ if default_is_wwan:
|
||||
print("WWAN is default")
|
||||
else:
|
||||
print("WWAN is not default")
|
||||
|
||||
|
@@ -12,6 +12,7 @@ import dbus
|
||||
|
||||
bus = dbus.SystemBus()
|
||||
|
||||
|
||||
def merge_secrets(proxy, config, setting_name):
|
||||
try:
|
||||
# returns a dict of dicts mapping name::setting, where setting is a dict
|
||||
@@ -25,6 +26,7 @@ def merge_secrets(proxy, config, setting_name):
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
|
||||
def dict_to_string(d, indent):
|
||||
# Try to trivially translate a dictionary's elements into nice string
|
||||
# formatting.
|
||||
@@ -48,6 +50,7 @@ def dict_to_string(d, indent):
|
||||
dstr += "%s%s: %s\n" % (indent, key, str_val)
|
||||
return dstr
|
||||
|
||||
|
||||
def connection_to_string(config):
|
||||
# dump a connection configuration to a the console
|
||||
for setting_name in config:
|
||||
@@ -66,29 +69,31 @@ def print_connections():
|
||||
# List each connection's name, UUID, and type
|
||||
for path in connection_paths:
|
||||
con_proxy = bus.get_object(service_name, path)
|
||||
settings_connection = dbus.Interface(con_proxy, "org.freedesktop.NetworkManager.Settings.Connection")
|
||||
settings_connection = dbus.Interface(
|
||||
con_proxy, "org.freedesktop.NetworkManager.Settings.Connection"
|
||||
)
|
||||
config = settings_connection.GetSettings()
|
||||
|
||||
# Now get secrets too; we grab the secrets for each type of connection
|
||||
# (since there isn't a "get all secrets" call because most of the time
|
||||
# you only need 'wifi' secrets or '802.1x' secrets, not everything) and
|
||||
# merge that into the configuration data
|
||||
merge_secrets(settings_connection, config, '802-11-wireless')
|
||||
merge_secrets(settings_connection, config, '802-11-wireless-security')
|
||||
merge_secrets(settings_connection, config, '802-1x')
|
||||
merge_secrets(settings_connection, config, 'gsm')
|
||||
merge_secrets(settings_connection, config, 'cdma')
|
||||
merge_secrets(settings_connection, config, 'ppp')
|
||||
merge_secrets(settings_connection, config, "802-11-wireless")
|
||||
merge_secrets(settings_connection, config, "802-11-wireless-security")
|
||||
merge_secrets(settings_connection, config, "802-1x")
|
||||
merge_secrets(settings_connection, config, "gsm")
|
||||
merge_secrets(settings_connection, config, "cdma")
|
||||
merge_secrets(settings_connection, config, "ppp")
|
||||
|
||||
# Get the details of the 'connection' setting
|
||||
s_con = config['connection']
|
||||
print(" name: %s" % s_con['id'])
|
||||
print(" uuid: %s" % s_con['uuid'])
|
||||
print(" type: %s" % s_con['type'])
|
||||
s_con = config["connection"]
|
||||
print(" name: %s" % s_con["id"])
|
||||
print(" uuid: %s" % s_con["uuid"])
|
||||
print(" type: %s" % s_con["type"])
|
||||
print(" ------------------------------------------")
|
||||
connection_to_string(config)
|
||||
|
||||
print("")
|
||||
|
||||
print_connections()
|
||||
|
||||
print_connections()
|
||||
|
@@ -9,44 +9,49 @@ import dbus
|
||||
# This example lists basic information about network interfaces known to NM
|
||||
|
||||
# For the types see include/NetworkManager.h
|
||||
devtypes = { 1: "Ethernet",
|
||||
2: "Wi-Fi",
|
||||
5: "Bluetooth",
|
||||
6: "OLPC",
|
||||
7: "WiMAX",
|
||||
8: "Modem",
|
||||
9: "InfiniBand",
|
||||
10: "Bond",
|
||||
11: "VLAN",
|
||||
12: "ADSL",
|
||||
13: "Bridge",
|
||||
14: "Generic",
|
||||
15: "Team",
|
||||
16: "TUN",
|
||||
17: "IPTunnel",
|
||||
18: "MACVLAN",
|
||||
19: "VXLAN",
|
||||
20: "Veth"
|
||||
}
|
||||
devtypes = {
|
||||
1: "Ethernet",
|
||||
2: "Wi-Fi",
|
||||
5: "Bluetooth",
|
||||
6: "OLPC",
|
||||
7: "WiMAX",
|
||||
8: "Modem",
|
||||
9: "InfiniBand",
|
||||
10: "Bond",
|
||||
11: "VLAN",
|
||||
12: "ADSL",
|
||||
13: "Bridge",
|
||||
14: "Generic",
|
||||
15: "Team",
|
||||
16: "TUN",
|
||||
17: "IPTunnel",
|
||||
18: "MACVLAN",
|
||||
19: "VXLAN",
|
||||
20: "Veth",
|
||||
}
|
||||
|
||||
states = { 0: "Unknown",
|
||||
10: "Unmanaged",
|
||||
20: "Unavailable",
|
||||
30: "Disconnected",
|
||||
40: "Prepare",
|
||||
50: "Config",
|
||||
60: "Need Auth",
|
||||
70: "IP Config",
|
||||
80: "IP Check",
|
||||
90: "Secondaries",
|
||||
100: "Activated",
|
||||
110: "Deactivating",
|
||||
120: "Failed" }
|
||||
states = {
|
||||
0: "Unknown",
|
||||
10: "Unmanaged",
|
||||
20: "Unavailable",
|
||||
30: "Disconnected",
|
||||
40: "Prepare",
|
||||
50: "Config",
|
||||
60: "Need Auth",
|
||||
70: "IP Config",
|
||||
80: "IP Check",
|
||||
90: "Secondaries",
|
||||
100: "Activated",
|
||||
110: "Deactivating",
|
||||
120: "Failed",
|
||||
}
|
||||
|
||||
bus = dbus.SystemBus()
|
||||
|
||||
# Get a proxy for the base NetworkManager object
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
|
||||
)
|
||||
manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
|
||||
|
||||
# Get all devices known to NM and print their properties
|
||||
@@ -57,18 +62,17 @@ for d in devices:
|
||||
props = prop_iface.GetAll("org.freedesktop.NetworkManager.Device")
|
||||
print("============================")
|
||||
|
||||
print("Interface: %s" % props['Interface'])
|
||||
print("Interface: %s" % props["Interface"])
|
||||
try:
|
||||
devtype = devtypes[props['DeviceType']]
|
||||
devtype = devtypes[props["DeviceType"]]
|
||||
except KeyError:
|
||||
devtype = "Unknown"
|
||||
print("Type: %s" % devtype)
|
||||
|
||||
print("Driver: %s" % props['Driver'])
|
||||
print("Driver: %s" % props["Driver"])
|
||||
|
||||
try:
|
||||
state = states[props['State']]
|
||||
state = states[props["State"]]
|
||||
except KeyError:
|
||||
state = "Unknown"
|
||||
print("State: %s" % state)
|
||||
|
||||
|
@@ -7,38 +7,46 @@
|
||||
import dbus
|
||||
|
||||
# Device states from include/NetworkManager.h
|
||||
device_states = { 0: "Unknown",
|
||||
10: "Unmanaged",
|
||||
20: "Unavailable",
|
||||
30: "Disconnected",
|
||||
40: "Prepare",
|
||||
50: "Config",
|
||||
60: "Need Auth",
|
||||
70: "IP Config",
|
||||
80: "IP Check",
|
||||
90: "Secondaries",
|
||||
100: "Activated",
|
||||
110: "Deactivating",
|
||||
120: "Failed" }
|
||||
device_states = {
|
||||
0: "Unknown",
|
||||
10: "Unmanaged",
|
||||
20: "Unavailable",
|
||||
30: "Disconnected",
|
||||
40: "Prepare",
|
||||
50: "Config",
|
||||
60: "Need Auth",
|
||||
70: "IP Config",
|
||||
80: "IP Check",
|
||||
90: "Secondaries",
|
||||
100: "Activated",
|
||||
110: "Deactivating",
|
||||
120: "Failed",
|
||||
}
|
||||
|
||||
connectivity_states = { 0: "Unknown",
|
||||
1: "Activating",
|
||||
2: "Activated",
|
||||
3: "Deactivating",
|
||||
4: "Deactivated" }
|
||||
connectivity_states = {
|
||||
0: "Unknown",
|
||||
1: "Activating",
|
||||
2: "Activated",
|
||||
3: "Deactivating",
|
||||
4: "Deactivated",
|
||||
}
|
||||
|
||||
nm_state = { 0: "Unknown",
|
||||
10: "Asleep",
|
||||
20: "Disconnected",
|
||||
30: "Disconnecting",
|
||||
40: "Connecting",
|
||||
50: "Connected-Local",
|
||||
60: "Connected-Site",
|
||||
70: "Connected-Global" }
|
||||
nm_state = {
|
||||
0: "Unknown",
|
||||
10: "Asleep",
|
||||
20: "Disconnected",
|
||||
30: "Disconnecting",
|
||||
40: "Connecting",
|
||||
50: "Connected-Local",
|
||||
60: "Connected-Site",
|
||||
70: "Connected-Global",
|
||||
}
|
||||
|
||||
bus = dbus.SystemBus()
|
||||
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
|
||||
)
|
||||
manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
|
||||
|
||||
# Get overall NM connection state
|
||||
@@ -55,7 +63,7 @@ for d in devices:
|
||||
name = prop_iface.Get("org.freedesktop.NetworkManager.Device", "Interface")
|
||||
|
||||
# and print them out
|
||||
if state == 100 : # activated
|
||||
if state == 100: # activated
|
||||
print("Device %s is activated" % name)
|
||||
else:
|
||||
print("Device %s is not activated (state=%s)" % (name, device_states[state]))
|
||||
@@ -72,10 +80,14 @@ for a in active:
|
||||
# Connections in NM are a collection of settings that describe everything
|
||||
# needed to connect to a specific network. Lets get those details so we
|
||||
# can find the user-readable name of the connection.
|
||||
con_path = prop_iface.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection")
|
||||
con_path = prop_iface.Get(
|
||||
"org.freedesktop.NetworkManager.Connection.Active", "Connection"
|
||||
)
|
||||
service_proxy = bus.get_object("org.freedesktop.NetworkManager", con_path)
|
||||
con_iface = dbus.Interface(service_proxy, "org.freedesktop.NetworkManager.Settings.Connection")
|
||||
con_iface = dbus.Interface(
|
||||
service_proxy, "org.freedesktop.NetworkManager.Settings.Connection"
|
||||
)
|
||||
con_details = con_iface.GetSettings()
|
||||
con_name = con_details['connection']['id']
|
||||
con_name = con_details["connection"]["id"]
|
||||
|
||||
print("Connection '%s' is %s" % (con_name, connectivity_states[state].lower()))
|
||||
|
@@ -14,7 +14,9 @@ import dbus
|
||||
bus = dbus.SystemBus()
|
||||
|
||||
# Get a proxy for the base NetworkManager object
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
|
||||
)
|
||||
manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
|
||||
|
||||
all_aps = []
|
||||
@@ -35,20 +37,26 @@ for d in devices:
|
||||
# Get device's type; we only want wifi devices
|
||||
iface = prop_iface.Get("org.freedesktop.NetworkManager.Device", "Interface")
|
||||
dtype = prop_iface.Get("org.freedesktop.NetworkManager.Device", "DeviceType")
|
||||
if dtype == 2: # WiFi
|
||||
if dtype == 2: # WiFi
|
||||
# Get a proxy for the wifi interface
|
||||
wifi_iface = dbus.Interface(dev_proxy, "org.freedesktop.NetworkManager.Device.Wireless")
|
||||
wifi_iface = dbus.Interface(
|
||||
dev_proxy, "org.freedesktop.NetworkManager.Device.Wireless"
|
||||
)
|
||||
wifi_prop_iface = dbus.Interface(dev_proxy, "org.freedesktop.DBus.Properties")
|
||||
|
||||
# Get the associated AP's object path
|
||||
connected_path = wifi_prop_iface.Get("org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint")
|
||||
connected_path = wifi_prop_iface.Get(
|
||||
"org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint"
|
||||
)
|
||||
|
||||
# Get all APs the card can see
|
||||
aps = wifi_iface.GetAccessPoints()
|
||||
for path in aps:
|
||||
ap_proxy = bus.get_object("org.freedesktop.NetworkManager", path)
|
||||
ap_prop_iface = dbus.Interface(ap_proxy, "org.freedesktop.DBus.Properties")
|
||||
bssid = ap_prop_iface.Get("org.freedesktop.NetworkManager.AccessPoint", "HwAddress")
|
||||
bssid = ap_prop_iface.Get(
|
||||
"org.freedesktop.NetworkManager.AccessPoint", "HwAddress"
|
||||
)
|
||||
|
||||
# Cache the BSSID
|
||||
if not bssid in all_aps:
|
||||
@@ -62,4 +70,3 @@ for d in devices:
|
||||
print("\nFound APs:")
|
||||
for bssid in all_aps:
|
||||
print(bssid)
|
||||
|
||||
|
@@ -30,42 +30,49 @@ if method == "static":
|
||||
method = "manual"
|
||||
|
||||
bus = dbus.SystemBus()
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings"
|
||||
)
|
||||
settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
|
||||
|
||||
for c_path in settings.ListConnections():
|
||||
c_proxy = bus.get_object("org.freedesktop.NetworkManager", c_path)
|
||||
c_obj = dbus.Interface(c_proxy, "org.freedesktop.NetworkManager.Settings.Connection")
|
||||
c_obj = dbus.Interface(
|
||||
c_proxy, "org.freedesktop.NetworkManager.Settings.Connection"
|
||||
)
|
||||
c_settings = c_obj.GetSettings()
|
||||
|
||||
# Look for the requested connection UUID
|
||||
if c_settings['connection']['uuid'] != sys.argv[1]:
|
||||
if c_settings["connection"]["uuid"] != sys.argv[1]:
|
||||
continue
|
||||
|
||||
# add IPv4 setting if it doesn't yet exist
|
||||
if 'ipv4' not in c_settings:
|
||||
c_settings['ipv4'] = {}
|
||||
if "ipv4" not in c_settings:
|
||||
c_settings["ipv4"] = {}
|
||||
|
||||
# clear existing address info
|
||||
if c_settings['ipv4'].has_key('addresses'):
|
||||
del c_settings['ipv4']['addresses']
|
||||
if c_settings['ipv4'].has_key('address-data'):
|
||||
del c_settings['ipv4']['address-data']
|
||||
if c_settings['ipv4'].has_key('gateway'):
|
||||
del c_settings['ipv4']['gateway']
|
||||
if c_settings["ipv4"].has_key("addresses"):
|
||||
del c_settings["ipv4"]["addresses"]
|
||||
if c_settings["ipv4"].has_key("address-data"):
|
||||
del c_settings["ipv4"]["address-data"]
|
||||
if c_settings["ipv4"].has_key("gateway"):
|
||||
del c_settings["ipv4"]["gateway"]
|
||||
|
||||
# set the method and change properties
|
||||
c_settings['ipv4']['method'] = method
|
||||
c_settings["ipv4"]["method"] = method
|
||||
if method == "manual":
|
||||
# Add the static IP address, prefix, and (optional) gateway
|
||||
addr = dbus.Dictionary({'address': sys.argv[3], 'prefix': dbus.UInt32(int(sys.argv[4]))})
|
||||
c_settings['ipv4']['address-data'] = dbus.Array([addr], signature=dbus.Signature('a{sv}'))
|
||||
addr = dbus.Dictionary(
|
||||
{"address": sys.argv[3], "prefix": dbus.UInt32(int(sys.argv[4]))}
|
||||
)
|
||||
c_settings["ipv4"]["address-data"] = dbus.Array(
|
||||
[addr], signature=dbus.Signature("a{sv}")
|
||||
)
|
||||
if len(sys.argv) == 6:
|
||||
c_settings['ipv4']['gateway'] = sys.argv[5]
|
||||
c_settings["ipv4"]["gateway"] = sys.argv[5]
|
||||
|
||||
# Save all the updated settings back to NetworkManager
|
||||
c_obj.Update(c_settings)
|
||||
break
|
||||
|
||||
sys.exit(0)
|
||||
|
||||
|
@@ -18,6 +18,7 @@ import sys
|
||||
|
||||
bus = dbus.SystemBus()
|
||||
|
||||
|
||||
def change_secrets_in_one_setting(proxy, config, setting_name):
|
||||
# Add new secret values to the connection config
|
||||
try:
|
||||
@@ -29,50 +30,62 @@ def change_secrets_in_one_setting(proxy, config, setting_name):
|
||||
# Ask user for new secrets and put them into our connection config
|
||||
for setting in secrets:
|
||||
for key in secrets[setting]:
|
||||
new_secret = raw_input ("Enter new secret for '%s' in '%s': " % (key, setting))
|
||||
new_secret = raw_input(
|
||||
"Enter new secret for '%s' in '%s': " % (key, setting)
|
||||
)
|
||||
config[setting_name][key] = new_secret
|
||||
except Exception as e:
|
||||
#code = str(e).split(':')[0]
|
||||
#print("Exception:" + str(e))
|
||||
# code = str(e).split(':')[0]
|
||||
# print("Exception:" + str(e))
|
||||
pass
|
||||
|
||||
|
||||
def change_secrets(con_path, config):
|
||||
# Get existing secrets; we grab the secrets for each type of connection
|
||||
# (since there isn't a "get all secrets" call because most of the time
|
||||
# you only need 'wifi' secrets or '802.1x' secrets, not everything) and
|
||||
# set new values into the connection settings (config)
|
||||
con_proxy = bus.get_object("org.freedesktop.NetworkManager", con_path)
|
||||
connection_secrets = dbus.Interface(con_proxy, "org.freedesktop.NetworkManager.Settings.Connection")
|
||||
change_secrets_in_one_setting(connection_secrets, config, '802-11-wireless')
|
||||
change_secrets_in_one_setting(connection_secrets, config, '802-11-wireless-security')
|
||||
change_secrets_in_one_setting(connection_secrets, config, '802-1x')
|
||||
change_secrets_in_one_setting(connection_secrets, config, 'gsm')
|
||||
change_secrets_in_one_setting(connection_secrets, config, 'cdma')
|
||||
change_secrets_in_one_setting(connection_secrets, config, 'ppp')
|
||||
connection_secrets = dbus.Interface(
|
||||
con_proxy, "org.freedesktop.NetworkManager.Settings.Connection"
|
||||
)
|
||||
change_secrets_in_one_setting(connection_secrets, config, "802-11-wireless")
|
||||
change_secrets_in_one_setting(
|
||||
connection_secrets, config, "802-11-wireless-security"
|
||||
)
|
||||
change_secrets_in_one_setting(connection_secrets, config, "802-1x")
|
||||
change_secrets_in_one_setting(connection_secrets, config, "gsm")
|
||||
change_secrets_in_one_setting(connection_secrets, config, "cdma")
|
||||
change_secrets_in_one_setting(connection_secrets, config, "ppp")
|
||||
|
||||
|
||||
def find_connection(name):
|
||||
# Ask the settings service for the list of connections it provides
|
||||
global con_path
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings"
|
||||
)
|
||||
settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
|
||||
connection_paths = settings.ListConnections()
|
||||
|
||||
# Get the settings and look for connection's name
|
||||
for path in connection_paths:
|
||||
con_proxy = bus.get_object("org.freedesktop.NetworkManager", path)
|
||||
connection = dbus.Interface(con_proxy, "org.freedesktop.NetworkManager.Settings.Connection")
|
||||
connection = dbus.Interface(
|
||||
con_proxy, "org.freedesktop.NetworkManager.Settings.Connection"
|
||||
)
|
||||
try:
|
||||
config = connection.GetSettings()
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
# Find connection by the id
|
||||
s_con = config['connection']
|
||||
if name == s_con['id']:
|
||||
s_con = config["connection"]
|
||||
if name == s_con["id"]:
|
||||
con_path = path
|
||||
return config
|
||||
# Find connection by the uuid
|
||||
if name == s_con['uuid']:
|
||||
if name == s_con["uuid"]:
|
||||
con_path = path
|
||||
return config
|
||||
|
||||
@@ -96,8 +109,9 @@ if con:
|
||||
|
||||
# Change the connection with Update()
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", con_path)
|
||||
settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings.Connection")
|
||||
settings = dbus.Interface(
|
||||
proxy, "org.freedesktop.NetworkManager.Settings.Connection"
|
||||
)
|
||||
settings.Update(con)
|
||||
else:
|
||||
sys.exit("No connection '%s' found" % sys.argv[1])
|
||||
|
||||
|
@@ -8,11 +8,11 @@
|
||||
# Run this script without any arguments to list the available connection uuids.
|
||||
|
||||
# The uuid of the connection to activate
|
||||
CONNECTION_UUID="ac6dc9b2-85ef-4311-83d8-add5d7db3f59"
|
||||
CONNECTION_UUID = "ac6dc9b2-85ef-4311-83d8-add5d7db3f59"
|
||||
|
||||
# UID to use. Note that NM only allows the owner of the connection to activate it.
|
||||
#UID=1000
|
||||
UID=0
|
||||
# UID=1000
|
||||
UID = 0
|
||||
|
||||
import sys
|
||||
import os
|
||||
@@ -22,20 +22,27 @@ import gobject
|
||||
|
||||
DBusGMainLoop(set_as_default=True)
|
||||
|
||||
|
||||
def get_connections():
|
||||
bus = dbus.SystemBus()
|
||||
proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager/Settings')
|
||||
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings')
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings"
|
||||
)
|
||||
iface = dbus.Interface(
|
||||
proxy, dbus_interface="org.freedesktop.NetworkManager.Settings"
|
||||
)
|
||||
return iface.ListConnections()
|
||||
|
||||
|
||||
def get_connection_by_uuid(uuid):
|
||||
bus = dbus.SystemBus()
|
||||
for c in get_connections():
|
||||
proxy = bus.get_object('org.freedesktop.NetworkManager', c)
|
||||
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings.Connection')
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", c)
|
||||
iface = dbus.Interface(
|
||||
proxy, dbus_interface="org.freedesktop.NetworkManager.Settings.Connection"
|
||||
)
|
||||
settings = iface.GetSettings()
|
||||
if settings['connection']['uuid'] == uuid:
|
||||
if settings["connection"]["uuid"] == uuid:
|
||||
return c
|
||||
|
||||
return None
|
||||
@@ -44,29 +51,39 @@ def get_connection_by_uuid(uuid):
|
||||
def list_uuids():
|
||||
bus = dbus.SystemBus()
|
||||
for c in get_connections():
|
||||
proxy = bus.get_object('org.freedesktop.NetworkManager', c)
|
||||
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings.Connection')
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", c)
|
||||
iface = dbus.Interface(
|
||||
proxy, dbus_interface="org.freedesktop.NetworkManager.Settings.Connection"
|
||||
)
|
||||
settings = iface.GetSettings()
|
||||
conn = settings['connection']
|
||||
print("%s - %s (%s)" % (conn['uuid'], conn['id'], conn['type']))
|
||||
conn = settings["connection"]
|
||||
print("%s - %s (%s)" % (conn["uuid"], conn["id"], conn["type"]))
|
||||
|
||||
|
||||
def get_active_connection_path(uuid):
|
||||
bus = dbus.SystemBus()
|
||||
proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
|
||||
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties')
|
||||
active_connections = iface.Get('org.freedesktop.NetworkManager', 'ActiveConnections')
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
|
||||
)
|
||||
iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.DBus.Properties")
|
||||
active_connections = iface.Get(
|
||||
"org.freedesktop.NetworkManager", "ActiveConnections"
|
||||
)
|
||||
|
||||
for a in active_connections:
|
||||
proxy = bus.get_object('org.freedesktop.NetworkManager', a)
|
||||
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties')
|
||||
path = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection')
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", a)
|
||||
iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.DBus.Properties")
|
||||
path = iface.Get(
|
||||
"org.freedesktop.NetworkManager.Connection.Active", "Connection"
|
||||
)
|
||||
|
||||
proxy = bus.get_object('org.freedesktop.NetworkManager', path)
|
||||
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager.Settings.Connection')
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", path)
|
||||
iface = dbus.Interface(
|
||||
proxy, dbus_interface="org.freedesktop.NetworkManager.Settings.Connection"
|
||||
)
|
||||
settings = iface.GetSettings()
|
||||
|
||||
if settings['connection']['uuid'] == uuid:
|
||||
if settings["connection"]["uuid"] == uuid:
|
||||
return a
|
||||
|
||||
return None
|
||||
@@ -74,19 +91,21 @@ def get_active_connection_path(uuid):
|
||||
|
||||
def get_wifi_device_path():
|
||||
bus = dbus.SystemBus()
|
||||
proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
|
||||
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager')
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
|
||||
)
|
||||
iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.NetworkManager")
|
||||
devices = iface.GetDevices()
|
||||
for d in devices:
|
||||
proxy = bus.get_object('org.freedesktop.NetworkManager', d)
|
||||
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties')
|
||||
devtype = iface.Get('org.freedesktop.NetworkManager.Device', 'DeviceType')
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager", d)
|
||||
iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.DBus.Properties")
|
||||
devtype = iface.Get("org.freedesktop.NetworkManager.Device", "DeviceType")
|
||||
if devtype == 2:
|
||||
return d
|
||||
return None
|
||||
|
||||
def activate_connection(connection_path, device_path):
|
||||
|
||||
def activate_connection(connection_path, device_path):
|
||||
def reply_handler(opath):
|
||||
print("Success: device activating")
|
||||
sys.exit(0)
|
||||
@@ -96,14 +115,18 @@ def activate_connection(connection_path, device_path):
|
||||
sys.exit(1)
|
||||
|
||||
bus = dbus.SystemBus()
|
||||
proxy = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
|
||||
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager')
|
||||
iface.ActivateConnection('org.freedesktop.NetworkManager',
|
||||
connection_path,
|
||||
device_path,
|
||||
"/",
|
||||
reply_handler=reply_handler,
|
||||
error_handler=error_handler)
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
|
||||
)
|
||||
iface = dbus.Interface(proxy, dbus_interface="org.freedesktop.NetworkManager")
|
||||
iface.ActivateConnection(
|
||||
"org.freedesktop.NetworkManager",
|
||||
connection_path,
|
||||
device_path,
|
||||
"/",
|
||||
reply_handler=reply_handler,
|
||||
error_handler=error_handler,
|
||||
)
|
||||
|
||||
|
||||
# Change the UID first if required
|
||||
@@ -135,4 +158,3 @@ print("Activating connection...")
|
||||
activate_connection(connection_path, device_path)
|
||||
loop = gobject.MainLoop()
|
||||
loop.run()
|
||||
|
||||
|
@@ -31,7 +31,9 @@ devpath = nm.GetDeviceByIpIface(iface)
|
||||
# Get a proxy to the wifi device and get the active access point's object path
|
||||
proxy = bus.get_object(service_name, devpath)
|
||||
props = dbus.Interface(proxy, "org.freedesktop.DBus.Properties")
|
||||
active_ap_path = props.Get("org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint")
|
||||
active_ap_path = props.Get(
|
||||
"org.freedesktop.NetworkManager.Device.Wireless", "ActiveAccessPoint"
|
||||
)
|
||||
if active_ap_path == "/":
|
||||
print("%s is not currently associated" % sys.argv[1])
|
||||
sys.exit(0)
|
||||
@@ -50,4 +52,3 @@ for c in raw_ssid:
|
||||
print("%s is associated to '%s' (%s)" % (sys.argv[1], ssid, bssid))
|
||||
|
||||
sys.exit(0)
|
||||
|
||||
|
@@ -13,38 +13,42 @@
|
||||
|
||||
import dbus, sys, time
|
||||
|
||||
our_uuid = '2b0d0f1d-b79d-43af-bde1-71744625642e'
|
||||
our_uuid = "2b0d0f1d-b79d-43af-bde1-71744625642e"
|
||||
|
||||
s_con = dbus.Dictionary({
|
||||
'type': '802-11-wireless',
|
||||
'uuid': our_uuid,
|
||||
'id': 'Test Hotspot'})
|
||||
s_con = dbus.Dictionary(
|
||||
{"type": "802-11-wireless", "uuid": our_uuid, "id": "Test Hotspot"}
|
||||
)
|
||||
|
||||
s_wifi = dbus.Dictionary({
|
||||
'ssid': dbus.ByteArray("My Hotspot".encode("utf-8")),
|
||||
'mode': "ap",
|
||||
'band': "bg",
|
||||
'channel': dbus.UInt32(1)})
|
||||
s_wifi = dbus.Dictionary(
|
||||
{
|
||||
"ssid": dbus.ByteArray("My Hotspot".encode("utf-8")),
|
||||
"mode": "ap",
|
||||
"band": "bg",
|
||||
"channel": dbus.UInt32(1),
|
||||
}
|
||||
)
|
||||
|
||||
s_wsec = dbus.Dictionary({
|
||||
'key-mgmt': 'wpa-psk',
|
||||
'psk': 'great password'})
|
||||
s_wsec = dbus.Dictionary({"key-mgmt": "wpa-psk", "psk": "great password"})
|
||||
|
||||
s_ip4 = dbus.Dictionary({'method': 'shared'})
|
||||
s_ip6 = dbus.Dictionary({'method': 'ignore'})
|
||||
s_ip4 = dbus.Dictionary({"method": "shared"})
|
||||
s_ip6 = dbus.Dictionary({"method": "ignore"})
|
||||
|
||||
con = dbus.Dictionary(
|
||||
{
|
||||
"connection": s_con,
|
||||
"802-11-wireless": s_wifi,
|
||||
"802-11-wireless-security": s_wsec,
|
||||
"ipv4": s_ip4,
|
||||
"ipv6": s_ip6,
|
||||
}
|
||||
)
|
||||
|
||||
con = dbus.Dictionary({
|
||||
'connection': s_con,
|
||||
'802-11-wireless': s_wifi,
|
||||
'802-11-wireless-security': s_wsec,
|
||||
'ipv4': s_ip4,
|
||||
'ipv6': s_ip6
|
||||
})
|
||||
|
||||
def usage():
|
||||
print("Usage: %s <ifname> [up|down]" % sys.argv[0])
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
bus = dbus.SystemBus()
|
||||
service_name = "org.freedesktop.NetworkManager"
|
||||
proxy = bus.get_object(service_name, "/org/freedesktop/NetworkManager/Settings")
|
||||
@@ -62,9 +66,11 @@ devpath = nm.GetDeviceByIpIface(iface)
|
||||
connection_path = None
|
||||
for path in settings.ListConnections():
|
||||
proxy = bus.get_object(service_name, path)
|
||||
settings_connection = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings.Connection")
|
||||
settings_connection = dbus.Interface(
|
||||
proxy, "org.freedesktop.NetworkManager.Settings.Connection"
|
||||
)
|
||||
config = settings_connection.GetSettings()
|
||||
if config['connection']['uuid'] == our_uuid:
|
||||
if config["connection"]["uuid"] == our_uuid:
|
||||
connection_path = path
|
||||
break
|
||||
|
||||
@@ -84,7 +90,9 @@ if operation == "up":
|
||||
# Wait for the hotspot to start up
|
||||
start = time.time()
|
||||
while time.time() < start + 10:
|
||||
state = active_props.Get("org.freedesktop.NetworkManager.Connection.Active", "State")
|
||||
state = active_props.Get(
|
||||
"org.freedesktop.NetworkManager.Connection.Active", "State"
|
||||
)
|
||||
if state == 2: # NM_ACTIVE_CONNECTION_STATE_ACTIVATED
|
||||
print("Access point started")
|
||||
sys.exit(0)
|
||||
@@ -96,4 +104,3 @@ else:
|
||||
usage()
|
||||
|
||||
sys.exit(0)
|
||||
|
||||
|
@@ -14,15 +14,18 @@
|
||||
#
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import GLib, NM
|
||||
import sys, uuid
|
||||
|
||||
main_loop = None
|
||||
|
||||
|
||||
def print_values(setting, key, value, flags, data):
|
||||
print(" %s.%s: %s" % (setting.get_name(), key, value))
|
||||
|
||||
|
||||
# create an Ethernet connection and return it
|
||||
def create_profile(name):
|
||||
profile = NM.SimpleConnection.new()
|
||||
@@ -49,6 +52,7 @@ def create_profile(name):
|
||||
|
||||
return profile
|
||||
|
||||
|
||||
# callback function
|
||||
def added_cb(client, result, data):
|
||||
try:
|
||||
@@ -58,16 +62,17 @@ def added_cb(client, result, data):
|
||||
sys.stderr.write("Error: %s\n" % e)
|
||||
main_loop.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# parse arguments
|
||||
persistent = False
|
||||
if len(sys.argv) != 2 and len(sys.argv) != 3:
|
||||
sys.exit('Usage: %s <connection name> [persistent]' % sys.argv[0])
|
||||
sys.exit("Usage: %s <connection name> [persistent]" % sys.argv[0])
|
||||
if len(sys.argv) == 3:
|
||||
if sys.argv[2] in "persistent" and sys.argv[2][:1] == "p":
|
||||
persistent = True
|
||||
else:
|
||||
sys.exit('Usage: %s <connection name> [persistent]' % sys.argv[0])
|
||||
sys.exit("Usage: %s <connection name> [persistent]" % sys.argv[0])
|
||||
profile_name = sys.argv[1]
|
||||
|
||||
main_loop = GLib.MainLoop()
|
||||
@@ -82,4 +87,3 @@ if __name__ == "__main__":
|
||||
client.add_connection_async(con, persistent, None, added_cb, None)
|
||||
|
||||
main_loop.run()
|
||||
|
||||
|
@@ -7,32 +7,52 @@
|
||||
import sys
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import GLib, NM
|
||||
|
||||
###############################################################################
|
||||
|
||||
|
||||
def usage():
|
||||
print("Usage: %s [COMMAND [ARG]...]" % sys.argv[0])
|
||||
print("")
|
||||
print(" COMMANDS: [show]")
|
||||
print(" create TIMEOUT [--destroy-all|--delete-new-connections|--disconnect-new-devices|--allow-overlapping|DEV]...")
|
||||
print(
|
||||
" create TIMEOUT [--destroy-all|--delete-new-connections|--disconnect-new-devices|--allow-overlapping|DEV]..."
|
||||
)
|
||||
print(" destroy PATH|NUMBER")
|
||||
print(" rollback PATH|NUMBER")
|
||||
print(" adjust-rollback-timeout PATH|NUMBER TIMEOUT")
|
||||
print("")
|
||||
sys.exit(1)
|
||||
|
||||
def show(c, ts = None):
|
||||
|
||||
def show(c, ts=None):
|
||||
cr = c.get_created()
|
||||
rt = c.get_rollback_timeout()
|
||||
print("%s:" % c.get_path())
|
||||
print(" created: %u%s" % (cr, "" if ts is None else (" (%s sec ago)" % ((ts - cr) / 1000.0))))
|
||||
print(
|
||||
" created: %u%s"
|
||||
% (cr, "" if ts is None else (" (%s sec ago)" % ((ts - cr) / 1000.0)))
|
||||
)
|
||||
if rt == 0:
|
||||
print(" timeout: infinity")
|
||||
else:
|
||||
print(" timeout: %u seconds%s" % (rt, "" if ts is None else (" (circa %s sec left)" % ((cr + (rt * 1000) - ts) / 1000.0))))
|
||||
print(" devices: %s" % (' '.join(sorted(map(lambda x: x.get_iface(), c.get_devices())))))
|
||||
print(
|
||||
" timeout: %u seconds%s"
|
||||
% (
|
||||
rt,
|
||||
""
|
||||
if ts is None
|
||||
else (" (circa %s sec left)" % ((cr + (rt * 1000) - ts) / 1000.0)),
|
||||
)
|
||||
)
|
||||
print(
|
||||
" devices: %s"
|
||||
% (" ".join(sorted(map(lambda x: x.get_iface(), c.get_devices()))))
|
||||
)
|
||||
|
||||
|
||||
def find_checkpoint(client, path):
|
||||
for c in client.get_checkpoints():
|
||||
@@ -40,6 +60,7 @@ def find_checkpoint(client, path):
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def validate_path(path, client):
|
||||
try:
|
||||
num = int(path)
|
||||
@@ -47,8 +68,8 @@ def validate_path(path, client):
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
if not path or path[0] != '/':
|
||||
sys.exit('Invalid checkpoint path \"%s\"' % (path))
|
||||
if not path or path[0] != "/":
|
||||
sys.exit('Invalid checkpoint path "%s"' % (path))
|
||||
|
||||
if client is not None:
|
||||
checkpoint = find_checkpoint(client, path)
|
||||
@@ -57,6 +78,7 @@ def validate_path(path, client):
|
||||
|
||||
return path
|
||||
|
||||
|
||||
def do_create(client):
|
||||
flags = NM.CheckpointCreateFlags.NONE
|
||||
if len(sys.argv) < 3:
|
||||
@@ -65,13 +87,13 @@ def do_create(client):
|
||||
timeout = int(sys.argv[2])
|
||||
devices = []
|
||||
for arg in sys.argv[3:]:
|
||||
if arg == '--destroy-all':
|
||||
if arg == "--destroy-all":
|
||||
flags |= NM.CheckpointCreateFlags.DESTROY_ALL
|
||||
elif arg == '--delete-new-connections':
|
||||
elif arg == "--delete-new-connections":
|
||||
flags |= NM.CheckpointCreateFlags.DELETE_NEW_CONNECTIONS
|
||||
elif arg == '--disconnect-new-devices':
|
||||
elif arg == "--disconnect-new-devices":
|
||||
flags |= NM.CheckpointCreateFlags.DISCONNECT_NEW_DEVICES
|
||||
elif arg == '--allow-overlapping':
|
||||
elif arg == "--allow-overlapping":
|
||||
flags |= NM.CheckpointCreateFlags.ALLOW_OVERLAPPING
|
||||
else:
|
||||
d = client.get_device_by_iface(arg)
|
||||
@@ -89,6 +111,7 @@ def do_create(client):
|
||||
|
||||
client.checkpoint_create(devices, timeout, flags, None, create_cb, None)
|
||||
|
||||
|
||||
def do_destroy(client):
|
||||
if len(sys.argv) < 3:
|
||||
sys.exit("Missing checkpoint path")
|
||||
@@ -105,6 +128,7 @@ def do_destroy(client):
|
||||
|
||||
client.checkpoint_destroy(path, None, destroy_cb, None)
|
||||
|
||||
|
||||
def do_rollback(client):
|
||||
if len(sys.argv) < 3:
|
||||
sys.exit("Missing checkpoint path")
|
||||
@@ -127,6 +151,7 @@ def do_rollback(client):
|
||||
|
||||
client.checkpoint_rollback(path, None, rollback_cb, None)
|
||||
|
||||
|
||||
def do_adjust_rollback_timeout(client):
|
||||
if len(sys.argv) < 3:
|
||||
sys.exit("Missing checkpoint path")
|
||||
@@ -147,27 +172,31 @@ def do_adjust_rollback_timeout(client):
|
||||
sys.stderr.write("Failed: %s\n" % e.message)
|
||||
main_loop.quit()
|
||||
|
||||
client.checkpoint_adjust_rollback_timeout(path, add_timeout, None, adjust_rollback_timeout_cb, None)
|
||||
client.checkpoint_adjust_rollback_timeout(
|
||||
path, add_timeout, None, adjust_rollback_timeout_cb, None
|
||||
)
|
||||
|
||||
|
||||
def do_show(client):
|
||||
ts = NM.utils_get_timestamp_msec()
|
||||
for c in client.get_checkpoints():
|
||||
show(c, ts)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
nm_client = NM.Client.new(None)
|
||||
main_loop = GLib.MainLoop()
|
||||
|
||||
if len(sys.argv) < 2 or sys.argv[1] == 'show':
|
||||
if len(sys.argv) < 2 or sys.argv[1] == "show":
|
||||
do_show(nm_client)
|
||||
sys.exit(0)
|
||||
elif sys.argv[1] == 'create':
|
||||
elif sys.argv[1] == "create":
|
||||
do_create(nm_client)
|
||||
elif sys.argv[1] == 'destroy':
|
||||
elif sys.argv[1] == "destroy":
|
||||
do_destroy(nm_client)
|
||||
elif sys.argv[1] == 'rollback':
|
||||
elif sys.argv[1] == "rollback":
|
||||
do_rollback(nm_client)
|
||||
elif sys.argv[1] == 'adjust-rollback-timeout':
|
||||
elif sys.argv[1] == "adjust-rollback-timeout":
|
||||
do_adjust_rollback_timeout(nm_client)
|
||||
else:
|
||||
usage()
|
||||
|
@@ -16,24 +16,25 @@
|
||||
|
||||
import sys
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import NM
|
||||
|
||||
# supported connection types
|
||||
connection_types = {
|
||||
NM.SETTING_VPN_SETTING_NAME,
|
||||
NM.SETTING_WIRELESS_SETTING_NAME,
|
||||
NM.SETTING_WIRED_SETTING_NAME,
|
||||
NM.SETTING_BOND_SETTING_NAME,
|
||||
NM.SETTING_BRIDGE_SETTING_NAME,
|
||||
NM.SETTING_TEAM_SETTING_NAME,
|
||||
NM.SETTING_INFINIBAND_SETTING_NAME,
|
||||
NM.SETTING_PPPOE_SETTING_NAME,
|
||||
NM.SETTING_ADSL_SETTING_NAME,
|
||||
NM.SETTING_BLUETOOTH_SETTING_NAME,
|
||||
NM.SETTING_WIMAX_SETTING_NAME,
|
||||
NM.SETTING_OLPC_MESH_SETTING_NAME,
|
||||
NM.SETTING_GENERIC_SETTING_NAME,
|
||||
NM.SETTING_VPN_SETTING_NAME,
|
||||
NM.SETTING_WIRELESS_SETTING_NAME,
|
||||
NM.SETTING_WIRED_SETTING_NAME,
|
||||
NM.SETTING_BOND_SETTING_NAME,
|
||||
NM.SETTING_BRIDGE_SETTING_NAME,
|
||||
NM.SETTING_TEAM_SETTING_NAME,
|
||||
NM.SETTING_INFINIBAND_SETTING_NAME,
|
||||
NM.SETTING_PPPOE_SETTING_NAME,
|
||||
NM.SETTING_ADSL_SETTING_NAME,
|
||||
NM.SETTING_BLUETOOTH_SETTING_NAME,
|
||||
NM.SETTING_WIMAX_SETTING_NAME,
|
||||
NM.SETTING_OLPC_MESH_SETTING_NAME,
|
||||
NM.SETTING_GENERIC_SETTING_NAME,
|
||||
}
|
||||
|
||||
|
||||
@@ -45,9 +46,14 @@ if __name__ == "__main__":
|
||||
if len(sys.argv) == 2:
|
||||
ctype = sys.argv[1]
|
||||
if ctype not in connection_types:
|
||||
sys.exit('Usage: %s [<type>]\nAllowed types: %s' % (sys.argv[0], allowed_types))
|
||||
sys.exit(
|
||||
"Usage: %s [<type>]\nAllowed types: %s"
|
||||
% (sys.argv[0], allowed_types)
|
||||
)
|
||||
else:
|
||||
sys.exit('Usage: %s [<type>]\nAllowed types: %s' % (sys.argv[0], allowed_types))
|
||||
sys.exit(
|
||||
"Usage: %s [<type>]\nAllowed types: %s" % (sys.argv[0], allowed_types)
|
||||
)
|
||||
|
||||
# create Client object
|
||||
client = NM.Client.new(None)
|
||||
@@ -63,5 +69,4 @@ if __name__ == "__main__":
|
||||
client.deactivate_connection(ac, None)
|
||||
sys.stdout.write("\033[32m -> succeeded\033[0m\n")
|
||||
except Exception as e:
|
||||
sys.stderr.write("\033[31m -> failed\033[0m (%s)\n" % e.message)
|
||||
|
||||
sys.stderr.write("\033[31m -> failed\033[0m (%s)\n" % e.message)
|
||||
|
@@ -6,7 +6,8 @@
|
||||
|
||||
import sys
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import GLib, NM
|
||||
|
||||
#
|
||||
@@ -18,6 +19,7 @@ from gi.repository import GLib, NM
|
||||
|
||||
main_loop = None
|
||||
|
||||
|
||||
def do_notify(self, property):
|
||||
print("notify: %s" % property)
|
||||
ip4cfg = self.get_ip4_config()
|
||||
@@ -25,26 +27,26 @@ def do_notify(self, property):
|
||||
print("ip4-config: %s" % ip4cfg.get_path())
|
||||
main_loop.quit()
|
||||
|
||||
|
||||
def state_changed(obj, arg1, arg2, arg3):
|
||||
print("State changed: New: %d, Old: %d, Reason: %d" % (arg1, arg2, arg3))
|
||||
# Device is connected
|
||||
if arg1 == 100:
|
||||
obj.connect('notify::ip4-config', do_notify)
|
||||
obj.connect("notify::ip4-config", do_notify)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit('Usage: %s <interface>' % sys.argv[0])
|
||||
sys.exit("Usage: %s <interface>" % sys.argv[0])
|
||||
dev_iface = sys.argv[1]
|
||||
|
||||
c = NM.Client.new(None)
|
||||
dev = c.get_device_by_iface(dev_iface)
|
||||
if dev is None:
|
||||
sys.exit('Device \'%s\' not found' % dev_iface)
|
||||
sys.exit("Device '%s' not found" % dev_iface)
|
||||
print("Device: %s - %s" % (dev_iface, dev.get_device_type().value_name))
|
||||
print("---------------------------------------")
|
||||
|
||||
dev.connect('state-changed', state_changed)
|
||||
dev.connect("state-changed", state_changed)
|
||||
main_loop = GLib.MainLoop()
|
||||
main_loop.run()
|
||||
|
||||
|
@@ -5,24 +5,26 @@
|
||||
#
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import GLib, NM
|
||||
|
||||
# This example shows how to monitor the DNS configuration
|
||||
|
||||
main_loop = None
|
||||
|
||||
|
||||
def handle_config(config):
|
||||
print " ---- new configuration ----"
|
||||
for entry in config:
|
||||
print " * servers: %s" % ', '.join(map(str, entry.get_nameservers()))
|
||||
print " * servers: %s" % ", ".join(map(str, entry.get_nameservers()))
|
||||
|
||||
domains = entry.get_domains()
|
||||
if domains and domains[0]:
|
||||
print " domains: %s" % ', '.join(map(str, domains))
|
||||
print " domains: %s" % ", ".join(map(str, domains))
|
||||
|
||||
if entry.get_interface():
|
||||
print " interface: %s" % entry.get_interface()
|
||||
print " interface: %s" % entry.get_interface()
|
||||
|
||||
print " priority: %d" % entry.get_priority()
|
||||
|
||||
@@ -31,9 +33,11 @@ def handle_config(config):
|
||||
|
||||
print ""
|
||||
|
||||
|
||||
def dns_config_changed(self, property):
|
||||
handle_config(self.get_dns_configuration())
|
||||
|
||||
|
||||
main_loop = None
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
@@ -6,7 +6,8 @@
|
||||
|
||||
import sys
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import GLib, NM
|
||||
|
||||
#
|
||||
@@ -26,13 +27,15 @@ from gi.repository import GLib, NM
|
||||
|
||||
main_loop = None
|
||||
|
||||
|
||||
def connection_saved(connection, error, data):
|
||||
print ("Connection '%s' saved.") % (connection.get_id())
|
||||
print("Connection '%s' saved.") % (connection.get_id())
|
||||
main_loop.quit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2 and len(sys.argv) != 3:
|
||||
sys.exit('Usage: %s <connection name or UUID> [new zone]' % sys.argv[0])
|
||||
sys.exit("Usage: %s <connection name or UUID> [new zone]" % sys.argv[0])
|
||||
|
||||
main_loop = GLib.MainLoop()
|
||||
client = NM.Client.new(None)
|
||||
|
@@ -7,7 +7,8 @@
|
||||
# This example lists currently active connections
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import NM
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -16,6 +17,4 @@ if __name__ == "__main__":
|
||||
for ac in acons:
|
||||
print("%s (%s) - %s" % (ac.get_id(), ac.get_uuid(), ac.get_connection_type()))
|
||||
if len(acons) == 0:
|
||||
print("No active connections")
|
||||
|
||||
|
||||
print("No active connections")
|
||||
|
@@ -7,7 +7,8 @@
|
||||
# This example lists all devices, both real and placeholder ones
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import NM
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -18,11 +19,18 @@ if __name__ == "__main__":
|
||||
print "------------"
|
||||
for d in devices:
|
||||
if d.is_real():
|
||||
print "%s (%s): %s" % (d.get_iface(), d.get_type_description(), d.get_state())
|
||||
print "%s (%s): %s" % (
|
||||
d.get_iface(),
|
||||
d.get_type_description(),
|
||||
d.get_state(),
|
||||
)
|
||||
|
||||
print "\nUnrealized/placeholder devices"
|
||||
print "------------------------------"
|
||||
for d in devices:
|
||||
if not d.is_real():
|
||||
print "%s (%s): %s" % (d.get_iface(), d.get_type_description(), d.get_state())
|
||||
|
||||
print "%s (%s): %s" % (
|
||||
d.get_iface(),
|
||||
d.get_type_description(),
|
||||
d.get_state(),
|
||||
)
|
||||
|
@@ -5,7 +5,8 @@
|
||||
#
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import NM
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -13,7 +14,10 @@ if __name__ == "__main__":
|
||||
devices = client.get_devices()
|
||||
|
||||
for d in devices:
|
||||
print("{:<16} {:<16} {}".format(d.get_iface(),
|
||||
"(" + d.get_type_description() + ")",
|
||||
NM.utils_enum_to_str(NM.DeviceInterfaceFlags,
|
||||
d.get_interface_flags())))
|
||||
print(
|
||||
"{:<16} {:<16} {}".format(
|
||||
d.get_iface(),
|
||||
"(" + d.get_type_description() + ")",
|
||||
NM.utils_enum_to_str(NM.DeviceInterfaceFlags, d.get_interface_flags()),
|
||||
)
|
||||
)
|
||||
|
@@ -6,7 +6,8 @@
|
||||
|
||||
import sys
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import GLib, NM
|
||||
|
||||
# This example shows how to get a list of LLDP neighbors for a given interface.
|
||||
@@ -15,24 +16,24 @@ main_loop = None
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit('Usage: %s <interface>' % sys.argv[0])
|
||||
sys.exit("Usage: %s <interface>" % sys.argv[0])
|
||||
dev_iface = sys.argv[1]
|
||||
|
||||
c = NM.Client.new(None)
|
||||
dev = c.get_device_by_iface(dev_iface)
|
||||
if dev is None:
|
||||
sys.exit('Device \'%s\' not found' % dev_iface)
|
||||
sys.exit("Device '%s' not found" % dev_iface)
|
||||
|
||||
neighbors = dev.get_lldp_neighbors()
|
||||
for neighbor in neighbors:
|
||||
ret, chassis = neighbor.get_attr_string_value('chassis-id')
|
||||
ret, port = neighbor.get_attr_string_value('port-id')
|
||||
ret, chassis = neighbor.get_attr_string_value("chassis-id")
|
||||
ret, port = neighbor.get_attr_string_value("port-id")
|
||||
print "Neighbor: %s - %s" % (chassis, port)
|
||||
for attr in neighbor.get_attr_names():
|
||||
attr_type = neighbor.get_attr_type(attr)
|
||||
if attr_type.equal(GLib.VariantType.new('s')):
|
||||
if attr_type.equal(GLib.VariantType.new("s")):
|
||||
ret, value = neighbor.get_attr_string_value(attr)
|
||||
print " %-32s: %s" % (attr, value)
|
||||
elif attr_type.equal(GLib.VariantType.new('u')):
|
||||
elif attr_type.equal(GLib.VariantType.new("u")):
|
||||
ret, value = neighbor.get_attr_uint_value(attr)
|
||||
print " %-32s: %u" % (attr, value)
|
||||
|
@@ -6,7 +6,8 @@
|
||||
|
||||
import sys, socket
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import NM
|
||||
|
||||
#
|
||||
@@ -14,11 +15,12 @@ from gi.repository import NM
|
||||
# from NMIP4Config and NMIP6Config (got out of NMDevice)
|
||||
#
|
||||
|
||||
|
||||
def show_addresses(dev, family):
|
||||
if (family == socket.AF_INET):
|
||||
ip_cfg = dev.get_ip4_config()
|
||||
if family == socket.AF_INET:
|
||||
ip_cfg = dev.get_ip4_config()
|
||||
else:
|
||||
ip_cfg = dev.get_ip6_config()
|
||||
ip_cfg = dev.get_ip6_config()
|
||||
|
||||
if ip_cfg is None:
|
||||
print("None")
|
||||
@@ -35,8 +37,9 @@ def show_addresses(dev, family):
|
||||
|
||||
print("%s/%d") % (addr, prefix)
|
||||
|
||||
|
||||
def show_gateway(dev, family):
|
||||
if (family == socket.AF_INET):
|
||||
if family == socket.AF_INET:
|
||||
ip_cfg = dev.get_ip4_config()
|
||||
else:
|
||||
ip_cfg = dev.get_ip6_config()
|
||||
@@ -45,16 +48,17 @@ def show_gateway(dev, family):
|
||||
gw = "None"
|
||||
else:
|
||||
gw = ip_cfg.get_gateway()
|
||||
if gw == '':
|
||||
if gw == "":
|
||||
gw = "None"
|
||||
|
||||
print(gw)
|
||||
|
||||
|
||||
def show_routes(dev, family):
|
||||
if (family == socket.AF_INET):
|
||||
ip_cfg = dev.get_ip4_config()
|
||||
if family == socket.AF_INET:
|
||||
ip_cfg = dev.get_ip4_config()
|
||||
else:
|
||||
ip_cfg = dev.get_ip6_config()
|
||||
ip_cfg = dev.get_ip6_config()
|
||||
|
||||
if ip_cfg is None:
|
||||
print("None")
|
||||
@@ -75,31 +79,31 @@ def show_routes(dev, family):
|
||||
|
||||
|
||||
def show_dns(dev, family):
|
||||
if (family == socket.AF_INET):
|
||||
ip_cfg = dev.get_ip4_config()
|
||||
if family == socket.AF_INET:
|
||||
ip_cfg = dev.get_ip4_config()
|
||||
else:
|
||||
ip_cfg = dev.get_ip6_config()
|
||||
ip_cfg = dev.get_ip6_config()
|
||||
|
||||
if ip_cfg is None:
|
||||
print("None")
|
||||
return
|
||||
|
||||
print ("Nameservers: %s") % (ip_cfg.get_nameservers())
|
||||
print ("Domains: %s") % (ip_cfg.get_domains())
|
||||
print ("Searches: %s") % (ip_cfg.get_searches())
|
||||
if (family == socket.AF_INET):
|
||||
print ("WINS: %s") % (ip_cfg.get_wins_servers())
|
||||
print("Nameservers: %s") % (ip_cfg.get_nameservers())
|
||||
print("Domains: %s") % (ip_cfg.get_domains())
|
||||
print("Searches: %s") % (ip_cfg.get_searches())
|
||||
if family == socket.AF_INET:
|
||||
print("WINS: %s") % (ip_cfg.get_wins_servers())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit('Usage: %s <interface>' % sys.argv[0])
|
||||
sys.exit("Usage: %s <interface>" % sys.argv[0])
|
||||
dev_iface = sys.argv[1]
|
||||
|
||||
c = NM.Client.new(None)
|
||||
dev = c.get_device_by_iface(dev_iface)
|
||||
if dev is None:
|
||||
sys.exit('Device \'%s\' not found' % dev_iface)
|
||||
sys.exit("Device '%s' not found" % dev_iface)
|
||||
print("Device: %s - %s" % (dev_iface, dev.get_device_type().value_name))
|
||||
print("---------------------------------------")
|
||||
|
||||
@@ -142,4 +146,3 @@ if __name__ == "__main__":
|
||||
print("------------")
|
||||
show_dns(dev, socket.AF_INET6)
|
||||
print
|
||||
|
||||
|
@@ -5,14 +5,17 @@
|
||||
#
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import NM
|
||||
|
||||
# This example asks settings service for all configured connections.
|
||||
|
||||
|
||||
def print_values(setting, key, value, flags, data):
|
||||
print(" %s.%s: %s" % (setting.get_name(), key, value))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# create Client object
|
||||
client = NM.Client.new(None)
|
||||
@@ -25,4 +28,3 @@ if __name__ == "__main__":
|
||||
print("=== %s : %s ===" % (c.get_id(), c.get_path()))
|
||||
c.for_each_setting_value(print_values, None)
|
||||
print("\n")
|
||||
|
||||
|
@@ -7,40 +7,47 @@
|
||||
import sys
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import GLib, NM
|
||||
|
||||
|
||||
def find_connections(nm_client, arg_type, arg_id):
|
||||
for c in nm_client.get_connections():
|
||||
if arg_type in [None, 'id'] and c.get_id() == arg_id:
|
||||
if arg_type in [None, "id"] and c.get_id() == arg_id:
|
||||
yield c
|
||||
if arg_type in [None, 'uuid'] and c.get_uuid() == arg_id:
|
||||
if arg_type in [None, "uuid"] and c.get_uuid() == arg_id:
|
||||
yield c
|
||||
|
||||
|
||||
def find_connection_first(nm_client, arg_type, arg_id):
|
||||
for f in find_connections(nm_client, arg_type, arg_id):
|
||||
return f
|
||||
|
||||
|
||||
def con_to_str(con):
|
||||
s_con = con.get_setting_connection()
|
||||
return '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid())
|
||||
|
||||
|
||||
def usage():
|
||||
arg0 = sys.argv[0]
|
||||
arg0_spaced = ' ' * len(arg0)
|
||||
print('Usage: %s [ --clone ( [id] <id> | [uuid] <uuid> ) ] \\' % (arg0))
|
||||
print(' %s [ --to-disk | --in-memory ] \\' % (arg0_spaced))
|
||||
print(' %s [ --block-autoconnect ] \\' % (arg0_spaced))
|
||||
print(' %s [ --id <new-id> ] \\' % (arg0_spaced))
|
||||
print(' %s [ --uuid <new-uuid> ] \\' % (arg0_spaced))
|
||||
arg0_spaced = " " * len(arg0)
|
||||
print("Usage: %s [ --clone ( [id] <id> | [uuid] <uuid> ) ] \\" % (arg0))
|
||||
print(" %s [ --to-disk | --in-memory ] \\" % (arg0_spaced))
|
||||
print(" %s [ --block-autoconnect ] \\" % (arg0_spaced))
|
||||
print(" %s [ --id <new-id> ] \\" % (arg0_spaced))
|
||||
print(" %s [ --uuid <new-uuid> ] \\" % (arg0_spaced))
|
||||
return 1
|
||||
|
||||
|
||||
def die(msg, print_usage=False):
|
||||
print(msg)
|
||||
if print_usage:
|
||||
usage()
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
main_loop = GLib.MainLoop()
|
||||
@@ -56,56 +63,62 @@ def main():
|
||||
|
||||
argv = list(sys.argv[1:])
|
||||
while argv:
|
||||
if argv[0] == '--clone':
|
||||
if argv[0] == "--clone":
|
||||
match_type = None
|
||||
if len(argv) < 2:
|
||||
die('missing argument for --clone option')
|
||||
if argv[0] in ['id', 'uuid']:
|
||||
die("missing argument for --clone option")
|
||||
if argv[0] in ["id", "uuid"]:
|
||||
match_type = argv[0]
|
||||
if len(argv) < 3:
|
||||
die('missing argument for "--clone %s" option' % (match_type))
|
||||
argv = argv[1:]
|
||||
if cons:
|
||||
die('cannot specify --clone argument more than once')
|
||||
die("cannot specify --clone argument more than once")
|
||||
cons.extend(find_connections(nm_client, match_type, argv[1]))
|
||||
if len(cons) == 0:
|
||||
die('could not find connection for "--clone %s%s"' % ((match_type or ''), argv[1]))
|
||||
die(
|
||||
'could not find connection for "--clone %s%s"'
|
||||
% ((match_type or ""), argv[1])
|
||||
)
|
||||
if len(cons) != 1:
|
||||
die('could not find unique connection for "--clone %s%s"' % ((match_type or ''), argv[1]))
|
||||
die(
|
||||
'could not find unique connection for "--clone %s%s"'
|
||||
% ((match_type or ""), argv[1])
|
||||
)
|
||||
argv = argv[2:]
|
||||
continue
|
||||
if argv[0] in ['--block-autoconnect']:
|
||||
if argv[0] in ["--block-autoconnect"]:
|
||||
arg_block_autoconnect = NM.SettingsAddConnection2Flags.BLOCK_AUTOCONNECT
|
||||
argv = argv[1:]
|
||||
continue
|
||||
if argv[0] in ['--to-disk', '--in-memory']:
|
||||
if argv[0] == '--to-disk':
|
||||
if argv[0] in ["--to-disk", "--in-memory"]:
|
||||
if argv[0] == "--to-disk":
|
||||
v = NM.SettingsAddConnection2Flags.TO_DISK
|
||||
elif argv[0] == '--in-memory':
|
||||
elif argv[0] == "--in-memory":
|
||||
v = NM.SettingsAddConnection2Flags.IN_MEMORY
|
||||
else:
|
||||
assert(False)
|
||||
assert False
|
||||
if arg_mode is not None:
|
||||
die('duplicate storage modes ("%s")' % (argv[0]))
|
||||
arg_mode = v
|
||||
argv = argv[1:]
|
||||
continue
|
||||
if argv[0] in ['--id']:
|
||||
if argv[0] in ["--id"]:
|
||||
if len(argv) < 2:
|
||||
die('missing argument for --id option')
|
||||
die("missing argument for --id option")
|
||||
arg_id = argv[1]
|
||||
argv = argv[2:]
|
||||
continue
|
||||
if argv[0] in ['--uuid']:
|
||||
if argv[0] in ["--uuid"]:
|
||||
if len(argv) < 2:
|
||||
die('missing argument for --uuid option')
|
||||
die("missing argument for --uuid option")
|
||||
arg_uuid = argv[1]
|
||||
argv = argv[2:]
|
||||
continue
|
||||
die('unknown argument "%s"' % (argv[0]))
|
||||
|
||||
if len(cons) != 1:
|
||||
die('missing --clone argument', True)
|
||||
die("missing --clone argument", True)
|
||||
|
||||
con = cons[0]
|
||||
|
||||
@@ -117,31 +130,46 @@ def main():
|
||||
s_con.set_property(NM.SETTING_CONNECTION_UUID, arg_uuid or NM.utils_uuid_generate())
|
||||
|
||||
result = {}
|
||||
|
||||
def _add_connection2_cb(cl, async_result, user_data):
|
||||
try:
|
||||
c, r = nm_client.add_connection2_finish(async_result)
|
||||
except Exception as e:
|
||||
result['error'] = e
|
||||
result["error"] = e
|
||||
else:
|
||||
result['result'] = r
|
||||
result['connection'] = c
|
||||
result["result"] = r
|
||||
result["connection"] = c
|
||||
main_loop.quit()
|
||||
|
||||
nm_client.add_connection2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL),
|
||||
(arg_mode if arg_mode is not None else NM.SettingsAddConnection2Flags.TO_DISK)
|
||||
| arg_block_autoconnect,
|
||||
None,
|
||||
False,
|
||||
None,
|
||||
_add_connection2_cb,
|
||||
None)
|
||||
nm_client.add_connection2(
|
||||
con2.to_dbus(NM.ConnectionSerializationFlags.ALL),
|
||||
(arg_mode if arg_mode is not None else NM.SettingsAddConnection2Flags.TO_DISK)
|
||||
| arg_block_autoconnect,
|
||||
None,
|
||||
False,
|
||||
None,
|
||||
_add_connection2_cb,
|
||||
None,
|
||||
)
|
||||
|
||||
main_loop.run()
|
||||
|
||||
if 'error' in result:
|
||||
die('update connection %s failed [%s]: %s' % (con_to_str(con2), ' '.join(sys.argv), result['error']))
|
||||
if "error" in result:
|
||||
die(
|
||||
"update connection %s failed [%s]: %s"
|
||||
% (con_to_str(con2), " ".join(sys.argv), result["error"])
|
||||
)
|
||||
|
||||
print('update connection %s succeeded [%s]: %s, %s' % (con_to_str(con2), ' '.join(sys.argv), result['connection'].get_path(), result['result']))
|
||||
print(
|
||||
"update connection %s succeeded [%s]: %s, %s"
|
||||
% (
|
||||
con_to_str(con2),
|
||||
" ".join(sys.argv),
|
||||
result["connection"].get_path(),
|
||||
result["result"],
|
||||
)
|
||||
)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
@@ -11,33 +11,37 @@ import sys
|
||||
import re
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import GLib, NM
|
||||
|
||||
|
||||
def usage():
|
||||
print('Usage: %s [[id] <id>]' % (sys.argv[0]))
|
||||
print(' %s [[uuid] <uuid>]' % (sys.argv[0]))
|
||||
print("Usage: %s [[id] <id>]" % (sys.argv[0]))
|
||||
print(" %s [[uuid] <uuid>]" % (sys.argv[0]))
|
||||
return 1
|
||||
|
||||
|
||||
def find_connection(nm_client, arg_type, arg_id):
|
||||
for c in nm_client.get_connections():
|
||||
if arg_type in [None, 'id'] and c.get_id() == arg_id:
|
||||
if arg_type in [None, "id"] and c.get_id() == arg_id:
|
||||
return c
|
||||
if arg_type in [None, 'uuid'] and c.get_uuid() == arg_id:
|
||||
if arg_type in [None, "uuid"] and c.get_uuid() == arg_id:
|
||||
return c
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2 or len(sys.argv) > 3:
|
||||
return usage()
|
||||
if len(sys.argv) == 3:
|
||||
arg_type = sys.argv[1]
|
||||
arg_id = sys.argv[2]
|
||||
if arg_type not in ['id', 'uuid']:
|
||||
if arg_type not in ["id", "uuid"]:
|
||||
return usage()
|
||||
else:
|
||||
arg_type = None
|
||||
arg_id = sys.argv[1]
|
||||
arg_log = '%s"%s"' % ((' with %s ' % (arg_type)) if arg_type else '', arg_id)
|
||||
arg_log = '%s"%s"' % ((" with %s " % (arg_type)) if arg_type else "", arg_id)
|
||||
|
||||
main_loop = GLib.MainLoop()
|
||||
|
||||
@@ -45,57 +49,61 @@ def main():
|
||||
|
||||
con = find_connection(nm_client, arg_type, arg_id)
|
||||
if con is None:
|
||||
print('could not find a connection %s' % (arg_log))
|
||||
print("could not find a connection %s" % (arg_log))
|
||||
return 1
|
||||
|
||||
s_con = con.get_setting_connection()
|
||||
if s_con is None:
|
||||
print('connection %s has no [connection] setting' % (arg_log))
|
||||
print("connection %s has no [connection] setting" % (arg_log))
|
||||
return 1
|
||||
|
||||
arg_log = '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid())
|
||||
|
||||
stable_id = s_con.get_stable_id()
|
||||
if not stable_id:
|
||||
print('connection %s has no stable-id set' % (arg_log))
|
||||
print("connection %s has no stable-id set" % (arg_log))
|
||||
return 1
|
||||
|
||||
re_match = re.search('\A(.*)-([0-9]+)\Z', stable_id)
|
||||
re_match = re.search("\A(.*)-([0-9]+)\Z", stable_id)
|
||||
if not re_match:
|
||||
stable_id = stable_id + '-1'
|
||||
stable_id = stable_id + "-1"
|
||||
else:
|
||||
stable_id = re_match.group(1) + '-' + str(int(re_match.group(2)) + 1)
|
||||
stable_id = re_match.group(1) + "-" + str(int(re_match.group(2)) + 1)
|
||||
|
||||
con2 = NM.SimpleConnection.new_clone(con)
|
||||
s_con = con2.get_setting_connection()
|
||||
s_con.set_property(NM.SETTING_CONNECTION_STABLE_ID, stable_id)
|
||||
|
||||
result = {}
|
||||
|
||||
def _update2_cb(con, async_result, user_data):
|
||||
try:
|
||||
r = con.update2_finish(async_result)
|
||||
except Exception as e:
|
||||
result['error'] = e
|
||||
result["error"] = e
|
||||
else:
|
||||
result['result'] = r
|
||||
result["result"] = r
|
||||
main_loop.quit()
|
||||
|
||||
con.update2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL),
|
||||
NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT,
|
||||
None,
|
||||
None,
|
||||
_update2_cb,
|
||||
None)
|
||||
con.update2(
|
||||
con2.to_dbus(NM.ConnectionSerializationFlags.ALL),
|
||||
NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT,
|
||||
None,
|
||||
None,
|
||||
_update2_cb,
|
||||
None,
|
||||
)
|
||||
|
||||
main_loop.run()
|
||||
|
||||
if 'error' in result:
|
||||
print('update connection %s failed: %s' % (arg_log, result['error']))
|
||||
if "error" in result:
|
||||
print("update connection %s failed: %s" % (arg_log, result["error"]))
|
||||
return 1
|
||||
|
||||
print('update connection %s succeeded: %s' % (arg_log, result['result']))
|
||||
print("update connection %s succeeded: %s" % (arg_log, result["result"]))
|
||||
print('set stable-id to "%s"' % (stable_id))
|
||||
return 0
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
@@ -7,40 +7,50 @@
|
||||
import sys
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import GLib, NM
|
||||
|
||||
|
||||
def find_connections(nm_client, arg_type, arg_id):
|
||||
for c in nm_client.get_connections():
|
||||
if arg_type in [None, 'id'] and c.get_id() == arg_id:
|
||||
if arg_type in [None, "id"] and c.get_id() == arg_id:
|
||||
yield c
|
||||
if arg_type in [None, 'uuid'] and c.get_uuid() == arg_id:
|
||||
if arg_type in [None, "uuid"] and c.get_uuid() == arg_id:
|
||||
yield c
|
||||
|
||||
|
||||
def find_connection_first(nm_client, arg_type, arg_id):
|
||||
for f in find_connections(nm_client, arg_type, arg_id):
|
||||
return f
|
||||
|
||||
|
||||
def con_to_str(con):
|
||||
s_con = con.get_setting_connection()
|
||||
return '"%s" (%s)' % (s_con.get_id(), s_con.get_uuid())
|
||||
|
||||
|
||||
def usage():
|
||||
arg0 = sys.argv[0]
|
||||
arg0_spaced = ' ' * len(arg0)
|
||||
print('Usage: %s [ [id] <id> | [uuid] <uuid> ] \\' % (arg0))
|
||||
print(' %s [ --to-disk | --in-memory | --in-memory-detached | --in-memory-only ] \\' % (arg0_spaced))
|
||||
print(' %s [ --block-autoconnect ] \\' % (arg0_spaced))
|
||||
print(' %s [ --volatile ] \\' % (arg0_spaced))
|
||||
print(' %s [ --no-reapply ] \\' % (arg0_spaced))
|
||||
arg0_spaced = " " * len(arg0)
|
||||
print("Usage: %s [ [id] <id> | [uuid] <uuid> ] \\" % (arg0))
|
||||
print(
|
||||
" %s [ --to-disk | --in-memory | --in-memory-detached | --in-memory-only ] \\"
|
||||
% (arg0_spaced)
|
||||
)
|
||||
print(" %s [ --block-autoconnect ] \\" % (arg0_spaced))
|
||||
print(" %s [ --volatile ] \\" % (arg0_spaced))
|
||||
print(" %s [ --no-reapply ] \\" % (arg0_spaced))
|
||||
return 1
|
||||
|
||||
|
||||
def die(msg, print_usage=False):
|
||||
print(msg)
|
||||
if print_usage:
|
||||
usage()
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
main_loop = GLib.MainLoop()
|
||||
@@ -56,9 +66,9 @@ def main():
|
||||
|
||||
argv = list(sys.argv[1:])
|
||||
while argv:
|
||||
if argv[0] in ['id', 'uuid']:
|
||||
if argv[0] in ["id", "uuid"]:
|
||||
if cons:
|
||||
die('cannot specify multiple connections')
|
||||
die("cannot specify multiple connections")
|
||||
if len(argv) < 2:
|
||||
die('missing argument for "%s" specifier' % (argv[0]))
|
||||
cons.extend(find_connections(nm_client, argv[0], argv[1]))
|
||||
@@ -68,31 +78,36 @@ def main():
|
||||
die('could not find unique connection for "%s %s"' % (argv[0], argv[1]))
|
||||
argv = argv[2:]
|
||||
continue
|
||||
if argv[0] in ['--block-autoconnect']:
|
||||
if argv[0] in ["--block-autoconnect"]:
|
||||
arg_block_autoconnect = NM.SettingsUpdate2Flags.BLOCK_AUTOCONNECT
|
||||
argv = argv[1:]
|
||||
continue
|
||||
if argv[0] in ['--volatile']:
|
||||
if argv[0] in ["--volatile"]:
|
||||
arg_volatile = NM.SettingsUpdate2Flags.VOLATILE
|
||||
argv = argv[1:]
|
||||
continue
|
||||
if argv[0] in ['--no-reapply']:
|
||||
if argv[0] in ["--no-reapply"]:
|
||||
arg_no_reapply = NM.SettingsUpdate2Flags.NO_REAPPLY
|
||||
argv = argv[1:]
|
||||
continue
|
||||
if argv[0] in ['--to-disk', '--in-memory', '--in-memory-detached', '--in-memory-only']:
|
||||
if argv[0] == '--to-disk':
|
||||
if argv[0] in [
|
||||
"--to-disk",
|
||||
"--in-memory",
|
||||
"--in-memory-detached",
|
||||
"--in-memory-only",
|
||||
]:
|
||||
if argv[0] == "--to-disk":
|
||||
v = NM.SettingsUpdate2Flags.TO_DISK
|
||||
elif argv[0] == '--in-memory':
|
||||
elif argv[0] == "--in-memory":
|
||||
v = NM.SettingsUpdate2Flags.IN_MEMORY
|
||||
elif argv[0] == '--in-memory-detached':
|
||||
elif argv[0] == "--in-memory-detached":
|
||||
v = NM.SettingsUpdate2Flags.IN_MEMORY_DETACHED
|
||||
elif argv[0] == '--in-memory-only':
|
||||
elif argv[0] == "--in-memory-only":
|
||||
v = NM.SettingsUpdate2Flags.IN_MEMORY_ONLY
|
||||
elif argv[0] == '--keep':
|
||||
elif argv[0] == "--keep":
|
||||
v = NM.SettingsUpdate2Flags.NONE
|
||||
else:
|
||||
assert(False)
|
||||
assert False
|
||||
if arg_mode is not None:
|
||||
die('duplicate storage modes ("%s")' % (argv[0]))
|
||||
arg_mode = v
|
||||
@@ -102,45 +117,55 @@ def main():
|
||||
die('unknown argument "%s"' % (argv[0]))
|
||||
cons.extend(find_connections(nm_client, None, argv[0]))
|
||||
if len(cons) == 0:
|
||||
die('could not find connection for "%s"' % (argv[0]))
|
||||
die('could not find connection for "%s"' % (argv[0]))
|
||||
if len(cons) != 1:
|
||||
die('could not find unique connection for "%s"' % (argv[0]))
|
||||
die('could not find unique connection for "%s"' % (argv[0]))
|
||||
argv = argv[1:]
|
||||
continue
|
||||
|
||||
if len(cons) != 1:
|
||||
die('missing connection argument', True)
|
||||
die("missing connection argument", True)
|
||||
|
||||
con = cons[0]
|
||||
|
||||
con2 = NM.SimpleConnection.new_clone(con)
|
||||
|
||||
result = {}
|
||||
|
||||
def _update2_cb(con, async_result, user_data):
|
||||
try:
|
||||
r = con.update2_finish(async_result)
|
||||
except Exception as e:
|
||||
result['error'] = e
|
||||
result["error"] = e
|
||||
else:
|
||||
result['result'] = r
|
||||
result["result"] = r
|
||||
main_loop.quit()
|
||||
|
||||
con.update2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL),
|
||||
(arg_mode if arg_mode is not None else NM.SettingsUpdate2Flags.NONE)
|
||||
| arg_block_autoconnect
|
||||
| arg_volatile
|
||||
| arg_no_reapply,
|
||||
None,
|
||||
None,
|
||||
_update2_cb,
|
||||
None)
|
||||
con.update2(
|
||||
con2.to_dbus(NM.ConnectionSerializationFlags.ALL),
|
||||
(arg_mode if arg_mode is not None else NM.SettingsUpdate2Flags.NONE)
|
||||
| arg_block_autoconnect
|
||||
| arg_volatile
|
||||
| arg_no_reapply,
|
||||
None,
|
||||
None,
|
||||
_update2_cb,
|
||||
None,
|
||||
)
|
||||
|
||||
main_loop.run()
|
||||
|
||||
if 'error' in result:
|
||||
die('update connection %s failed [%s]: %s' % (con_to_str(con2), ' '.join(sys.argv), result['error']))
|
||||
if "error" in result:
|
||||
die(
|
||||
"update connection %s failed [%s]: %s"
|
||||
% (con_to_str(con2), " ".join(sys.argv), result["error"])
|
||||
)
|
||||
|
||||
print('update connection %s succeeded [%s]: %s' % (con_to_str(con2), ' '.join(sys.argv), result['result']))
|
||||
print(
|
||||
"update connection %s succeeded [%s]: %s"
|
||||
% (con_to_str(con2), " ".join(sys.argv), result["result"])
|
||||
)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
@@ -39,59 +39,60 @@ import sys
|
||||
import re
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import NM
|
||||
|
||||
|
||||
def pr(v):
|
||||
import pprint
|
||||
|
||||
pprint.pprint(v, indent=4, depth=5, width=60)
|
||||
|
||||
|
||||
def parse_args():
|
||||
args = {
|
||||
'set': False,
|
||||
'set-gobject': False,
|
||||
'filter': [],
|
||||
'data': []
|
||||
}
|
||||
args = {"set": False, "set-gobject": False, "filter": [], "data": []}
|
||||
i = 1
|
||||
while i < len(sys.argv):
|
||||
a = sys.argv[i]
|
||||
if i == 1:
|
||||
if a in ['s', 'set']:
|
||||
args['set'] = True
|
||||
if a in ["s", "set"]:
|
||||
args["set"] = True
|
||||
i += 1
|
||||
continue
|
||||
elif a in ['g', 'get']:
|
||||
args['set'] = False
|
||||
elif a in ["g", "get"]:
|
||||
args["set"] = False
|
||||
i += 1
|
||||
continue
|
||||
if a in ['id', 'uuid']:
|
||||
args['filter'].append((a, sys.argv[i+1]))
|
||||
if a in ["id", "uuid"]:
|
||||
args["filter"].append((a, sys.argv[i + 1]))
|
||||
i += 2
|
||||
continue
|
||||
|
||||
if a in ['--set-gobject']:
|
||||
args['set-gobject'] = True
|
||||
if a in ["--set-gobject"]:
|
||||
args["set-gobject"] = True
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if a == 'data':
|
||||
if a == "data":
|
||||
i += 1
|
||||
a = sys.argv[i]
|
||||
if args['set']:
|
||||
if a == '-d':
|
||||
args['data'].append((sys.argv[i+1], None))
|
||||
if args["set"]:
|
||||
if a == "-d":
|
||||
args["data"].append((sys.argv[i + 1], None))
|
||||
else:
|
||||
args['data'].append((a, sys.argv[i+1]))
|
||||
args["data"].append((a, sys.argv[i + 1]))
|
||||
i += 2
|
||||
else:
|
||||
args['data'].append(a)
|
||||
args["data"].append(a)
|
||||
i += 1
|
||||
|
||||
return args
|
||||
|
||||
|
||||
def connection_to_str(connection):
|
||||
return '%s (%s)' % (connection.get_id(), connection.get_uuid())
|
||||
return "%s (%s)" % (connection.get_id(), connection.get_uuid())
|
||||
|
||||
|
||||
def connections_filter(connections, filter_data):
|
||||
connections = list(sorted(connections, key=connection_to_str))
|
||||
@@ -102,20 +103,21 @@ def connections_filter(connections, filter_data):
|
||||
# them multiple times.
|
||||
l = []
|
||||
for f in filter_data:
|
||||
if f[0] == 'id':
|
||||
if f[0] == "id":
|
||||
for c in connections:
|
||||
if f[1] == c.get_id():
|
||||
l.append(c)
|
||||
else:
|
||||
assert(f[0] == 'uuid')
|
||||
assert f[0] == "uuid"
|
||||
for c in connections:
|
||||
if f[1] == c.get_uuid():
|
||||
l.append(c)
|
||||
return l
|
||||
|
||||
def print_user_data(connection, data_allow_regex, data, prefix=''):
|
||||
|
||||
def print_user_data(connection, data_allow_regex, data, prefix=""):
|
||||
s_u = connection.get_setting(NM.SettingUser)
|
||||
n = 'none'
|
||||
n = "none"
|
||||
keys_len = 0
|
||||
keys = []
|
||||
if s_u is not None:
|
||||
@@ -123,17 +125,17 @@ def print_user_data(connection, data_allow_regex, data, prefix=''):
|
||||
keys_len = len(all_keys)
|
||||
if data:
|
||||
for d in data:
|
||||
if data_allow_regex and len(d) > 0 and d[0] == '~':
|
||||
if data_allow_regex and len(d) > 0 and d[0] == "~":
|
||||
r = re.compile(d[1:])
|
||||
keys.extend([k for k in all_keys if r.match(k)])
|
||||
else:
|
||||
keys.append (d)
|
||||
keys.append(d)
|
||||
else:
|
||||
keys.extend(all_keys)
|
||||
n = '%s' % (keys_len)
|
||||
n = "%s" % (keys_len)
|
||||
|
||||
print('%s%s [%s]' % (prefix, connection_to_str(connection), n))
|
||||
dd = { }
|
||||
print("%s%s [%s]" % (prefix, connection_to_str(connection), n))
|
||||
dd = {}
|
||||
if s_u is not None:
|
||||
dd = s_u.get_property(NM.SETTING_USER_DATA)
|
||||
for k in keys:
|
||||
@@ -145,7 +147,7 @@ def print_user_data(connection, data_allow_regex, data, prefix=''):
|
||||
else:
|
||||
print('%s MISSING: "%s"' % (prefix, k))
|
||||
else:
|
||||
assert(v == dd.get(k, None))
|
||||
assert v == dd.get(k, None)
|
||||
print('%s SET: "%s" = "%s"' % (prefix, k, v))
|
||||
else:
|
||||
print('%s MISSING: "%s"' % (prefix, k))
|
||||
@@ -155,20 +157,19 @@ def do_get(connections, data):
|
||||
first_line = True
|
||||
connections = list(connections)
|
||||
if not connections:
|
||||
print('no matching connections (use id|uuid argument)')
|
||||
print("no matching connections (use id|uuid argument)")
|
||||
sys.exit(1)
|
||||
for c in connections:
|
||||
if first_line:
|
||||
first_line = False
|
||||
else:
|
||||
print('')
|
||||
print("")
|
||||
print_user_data(c, True, data)
|
||||
|
||||
|
||||
def do_set(connection, data, set_gobject):
|
||||
print_user_data(connection, False,
|
||||
[d[0] for d in data],
|
||||
prefix = 'BEFORE: ')
|
||||
print('')
|
||||
print_user_data(connection, False, [d[0] for d in data], prefix="BEFORE: ")
|
||||
print("")
|
||||
s_u = connection.get_setting(NM.SettingUser)
|
||||
if s_u is None:
|
||||
connection.add_setting(NM.SettingUser())
|
||||
@@ -197,35 +198,37 @@ def do_set(connection, data, set_gobject):
|
||||
print('error setting key "%s" = "%s": %s' % (key, val, e))
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
try:
|
||||
connection.commit_changes(True, None)
|
||||
except Exception as e:
|
||||
print('failure to commit connection: %s' % (e))
|
||||
print("failure to commit connection: %s" % (e))
|
||||
sys.exit(1)
|
||||
|
||||
print('')
|
||||
print_user_data(connection, False,
|
||||
[d[0] for d in data],
|
||||
prefix = 'AFTER: ')
|
||||
print("")
|
||||
print_user_data(connection, False, [d[0] for d in data], prefix="AFTER: ")
|
||||
|
||||
|
||||
###############################################################################
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
args = parse_args()
|
||||
nm_client = NM.Client.new(None)
|
||||
|
||||
connections = connections_filter(nm_client.get_connections(), args['filter'])
|
||||
connections = connections_filter(nm_client.get_connections(), args["filter"])
|
||||
|
||||
if args['set']:
|
||||
if not args['data']:
|
||||
print('Requires one or more arguments to set or delete')
|
||||
if args["set"]:
|
||||
if not args["data"]:
|
||||
print("Requires one or more arguments to set or delete")
|
||||
sys.exit(1)
|
||||
if len(connections) != 1:
|
||||
print('To set the user-data of a connection, exactly one connection must be selected via id|uuid. Instead, %s connection matched ([%s])' %
|
||||
(len(connections), ', '.join([connection_to_str(c) for c in connections])))
|
||||
print(
|
||||
"To set the user-data of a connection, exactly one connection must be selected via id|uuid. Instead, %s connection matched ([%s])"
|
||||
% (
|
||||
len(connections),
|
||||
", ".join([connection_to_str(c) for c in connections]),
|
||||
)
|
||||
)
|
||||
sys.exit(1)
|
||||
do_set(connections[0], args['data'], args['set-gobject'])
|
||||
do_set(connections[0], args["data"], args["set-gobject"])
|
||||
else:
|
||||
do_get(connections, args['data'])
|
||||
|
||||
do_get(connections, args["data"])
|
||||
|
@@ -7,7 +7,8 @@
|
||||
|
||||
import locale
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import NM
|
||||
|
||||
#
|
||||
@@ -19,40 +20,50 @@ from gi.repository import NM
|
||||
# an error without it: http://www.python.org/dev/peps/pep-0263/
|
||||
#
|
||||
|
||||
|
||||
def clamp(value, minvalue, maxvalue):
|
||||
return max(minvalue, min(value, maxvalue))
|
||||
|
||||
|
||||
def ssid_to_utf8(ap):
|
||||
ssid = ap.get_ssid()
|
||||
if not ssid:
|
||||
return ""
|
||||
return NM.utils_ssid_to_utf8(ap.get_ssid().get_data())
|
||||
|
||||
|
||||
def print_device_info(device):
|
||||
active_ap = dev.get_active_access_point()
|
||||
ssid = None
|
||||
if active_ap is not None:
|
||||
ssid = ssid_to_utf8(active_ap)
|
||||
info = "Device: %s | Driver: %s | Active AP: %s" % (dev.get_iface(), dev.get_driver(), ssid)
|
||||
info = "Device: %s | Driver: %s | Active AP: %s" % (
|
||||
dev.get_iface(),
|
||||
dev.get_driver(),
|
||||
ssid,
|
||||
)
|
||||
print(info)
|
||||
print('=' * len(info))
|
||||
print("=" * len(info))
|
||||
|
||||
|
||||
def mode_to_string(mode):
|
||||
if mode == getattr(NM, '80211Mode').INFRA:
|
||||
if mode == getattr(NM, "80211Mode").INFRA:
|
||||
return "INFRA"
|
||||
if mode == getattr(NM, '80211Mode').ADHOC:
|
||||
if mode == getattr(NM, "80211Mode").ADHOC:
|
||||
return "ADHOC"
|
||||
if mode == getattr(NM, '80211Mode').AP:
|
||||
if mode == getattr(NM, "80211Mode").AP:
|
||||
return "AP"
|
||||
return "UNKNOWN"
|
||||
|
||||
|
||||
def flags_to_string(flags):
|
||||
if flags & getattr(NM, '80211ApFlags').PRIVACY:
|
||||
if flags & getattr(NM, "80211ApFlags").PRIVACY:
|
||||
return "PRIVACY"
|
||||
return "NONE"
|
||||
|
||||
|
||||
def security_flags_to_string(flags):
|
||||
NM_AP_FLAGS = getattr(NM, '80211ApSecurityFlags')
|
||||
NM_AP_FLAGS = getattr(NM, "80211ApSecurityFlags")
|
||||
str = ""
|
||||
if flags & NM_AP_FLAGS.PAIR_WEP40:
|
||||
str = str + " PAIR_WEP40"
|
||||
@@ -79,43 +90,50 @@ def security_flags_to_string(flags):
|
||||
else:
|
||||
return "NONE"
|
||||
|
||||
|
||||
def flags_to_security(flags, wpa_flags, rsn_flags):
|
||||
str = ""
|
||||
if ((flags & getattr(NM, '80211ApFlags').PRIVACY) and
|
||||
(wpa_flags == 0) and (rsn_flags == 0)):
|
||||
str = str + " WEP"
|
||||
if (
|
||||
(flags & getattr(NM, "80211ApFlags").PRIVACY)
|
||||
and (wpa_flags == 0)
|
||||
and (rsn_flags == 0)
|
||||
):
|
||||
str = str + " WEP"
|
||||
if wpa_flags != 0:
|
||||
str = str + " WPA1"
|
||||
if rsn_flags != 0:
|
||||
str = str + " WPA2"
|
||||
if ((wpa_flags & getattr(NM, '80211ApSecurityFlags').KEY_MGMT_802_1X) or
|
||||
(rsn_flags & getattr(NM, '80211ApSecurityFlags').KEY_MGMT_802_1X)):
|
||||
if (wpa_flags & getattr(NM, "80211ApSecurityFlags").KEY_MGMT_802_1X) or (
|
||||
rsn_flags & getattr(NM, "80211ApSecurityFlags").KEY_MGMT_802_1X
|
||||
):
|
||||
str = str + " 802.1X"
|
||||
return str.lstrip()
|
||||
|
||||
|
||||
def print_ap_info(ap):
|
||||
strength = ap.get_strength()
|
||||
frequency = ap.get_frequency()
|
||||
flags = ap.get_flags()
|
||||
wpa_flags = ap.get_wpa_flags()
|
||||
rsn_flags = ap.get_rsn_flags()
|
||||
print("SSID: %s" % (ssid_to_utf8(ap)))
|
||||
print("BSSID: %s" % (ap.get_bssid()))
|
||||
print("Frequency: %s" % (frequency))
|
||||
print("Channel: %s" % (NM.utils_wifi_freq_to_channel(frequency)))
|
||||
print("Mode: %s" % (mode_to_string(ap.get_mode())))
|
||||
print("Flags: %s" % (flags_to_string(flags)))
|
||||
print("WPA flags: %s" % (security_flags_to_string(wpa_flags)))
|
||||
print("RSN flags: %s" % (security_flags_to_string(rsn_flags)))
|
||||
print("Security: %s" % (flags_to_security(flags, wpa_flags, rsn_flags)))
|
||||
print("SSID: %s" % (ssid_to_utf8(ap)))
|
||||
print("BSSID: %s" % (ap.get_bssid()))
|
||||
print("Frequency: %s" % (frequency))
|
||||
print("Channel: %s" % (NM.utils_wifi_freq_to_channel(frequency)))
|
||||
print("Mode: %s" % (mode_to_string(ap.get_mode())))
|
||||
print("Flags: %s" % (flags_to_string(flags)))
|
||||
print("WPA flags: %s" % (security_flags_to_string(wpa_flags)))
|
||||
print("RSN flags: %s" % (security_flags_to_string(rsn_flags)))
|
||||
print("Security: %s" % (flags_to_security(flags, wpa_flags, rsn_flags)))
|
||||
print("Strength: %s %s%%" % (NM.utils_wifi_strength_bars(strength), strength))
|
||||
print
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Python apparently doesn't call setlocale() on its own? We have to call this or else
|
||||
# NM.utils_wifi_strength_bars() will think the locale is ASCII-only, and return the
|
||||
# fallback characters rather than the unicode bars
|
||||
locale.setlocale(locale.LC_ALL, '')
|
||||
locale.setlocale(locale.LC_ALL, "")
|
||||
|
||||
nmc = NM.Client.new(None)
|
||||
devs = nmc.get_devices()
|
||||
@@ -125,4 +143,3 @@ if __name__ == "__main__":
|
||||
print_device_info(dev)
|
||||
for ap in dev.get_access_points():
|
||||
print_ap_info(ap)
|
||||
|
||||
|
@@ -13,7 +13,8 @@
|
||||
#
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import GLib, NM
|
||||
import sys, socket
|
||||
|
||||
@@ -25,7 +26,9 @@ if __name__ == "__main__":
|
||||
|
||||
method = sys.argv[2]
|
||||
if (method == "static" or method == "manual") and len(sys.argv) < 5:
|
||||
print("Usage: %s %s static address prefix [gateway]" % (sys.argv[0], sys.argv[1]))
|
||||
print(
|
||||
"Usage: %s %s static address prefix [gateway]" % (sys.argv[0], sys.argv[1])
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
uuid = sys.argv[1]
|
||||
@@ -69,4 +72,3 @@ if __name__ == "__main__":
|
||||
except Exception as e:
|
||||
sys.stderr.write("Error: %s\n" % e)
|
||||
break
|
||||
|
||||
|
@@ -9,7 +9,8 @@
|
||||
# VPN plugin.
|
||||
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import GLib, NM
|
||||
|
||||
import sys
|
||||
@@ -35,17 +36,21 @@ for vpn_info in NM.VpnPluginInfo.list_load():
|
||||
break
|
||||
|
||||
if connection is None:
|
||||
print("None of the VPN plugins was able to import \"%s\"" % (filename))
|
||||
print('None of the VPN plugins was able to import "%s"' % (filename))
|
||||
sys.exit(1)
|
||||
|
||||
connection.normalize()
|
||||
|
||||
print("connection imported from \"%s\" using plugin \"%s\" (\"%s\", %s)" % (filename, vpn_info.get_filename(), connection.get_id(), connection.get_uuid()))
|
||||
print(
|
||||
'connection imported from "%s" using plugin "%s" ("%s", %s)'
|
||||
% (filename, vpn_info.get_filename(), connection.get_id(), connection.get_uuid())
|
||||
)
|
||||
|
||||
client = NM.Client.new(None)
|
||||
|
||||
main_loop = GLib.MainLoop()
|
||||
|
||||
|
||||
def added_cb(client, result, data):
|
||||
try:
|
||||
client.add_connection_finish(result)
|
||||
@@ -54,6 +59,7 @@ def added_cb(client, result, data):
|
||||
print("ERROR: failed to add connection: %s\n" % e)
|
||||
main_loop.quit()
|
||||
|
||||
|
||||
client.add_connection_async(connection, True, None, added_cb, None)
|
||||
|
||||
main_loop.run()
|
||||
|
@@ -9,12 +9,14 @@
|
||||
import sys
|
||||
import uuid
|
||||
import gi
|
||||
gi.require_version('NM', '1.0')
|
||||
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import GLib, NM
|
||||
|
||||
main_loop = None
|
||||
client = None
|
||||
|
||||
|
||||
def create_profile(name, peer_mac):
|
||||
profile = NM.SimpleConnection.new()
|
||||
|
||||
@@ -32,8 +34,10 @@ def create_profile(name, peer_mac):
|
||||
|
||||
s_wifi_p2p = NM.SettingWifiP2P.new()
|
||||
s_wifi_p2p.set_property(NM.SETTING_WIFI_P2P_PEER, peer_mac)
|
||||
s_wifi_p2p.set_property(NM.SETTING_WIFI_P2P_WFD_IES,
|
||||
GLib.Bytes.new(b'\x00\x00\x06\x00\x90\x1c\x44\x00\xc8'))
|
||||
s_wifi_p2p.set_property(
|
||||
NM.SETTING_WIFI_P2P_WFD_IES,
|
||||
GLib.Bytes.new(b"\x00\x00\x06\x00\x90\x1c\x44\x00\xc8"),
|
||||
)
|
||||
|
||||
profile.add_setting(s_con)
|
||||
profile.add_setting(s_ip4)
|
||||
@@ -42,6 +46,7 @@ def create_profile(name, peer_mac):
|
||||
|
||||
return profile
|
||||
|
||||
|
||||
def activated_cb(client, result, data):
|
||||
try:
|
||||
client.add_and_activate_connection2_finish(result)
|
||||
@@ -50,35 +55,37 @@ def activated_cb(client, result, data):
|
||||
sys.stderr.write("Error: %s\n" % e)
|
||||
main_loop.quit()
|
||||
|
||||
|
||||
def scan_timeout_cb(device):
|
||||
peers = device.get_peers()
|
||||
if len(peers) == 0:
|
||||
main_loop.quit()
|
||||
sys.exit("No peer found")
|
||||
|
||||
print("\n {:20} {:30} {:3} {:30}".format("MAC", "Name", "Sig", "Wfd-IEs"));
|
||||
print("\n {:20} {:30} {:3} {:30}".format("MAC", "Name", "Sig", "Wfd-IEs"))
|
||||
for p in peers:
|
||||
if p.get_wfd_ies() is not None:
|
||||
ies = p.get_wfd_ies().get_data().hex()
|
||||
else:
|
||||
ies = ""
|
||||
print(" {:20} {:30} {:3} {:30}".format(p.get_hw_address(),
|
||||
p.get_name(),
|
||||
p.get_strength(),
|
||||
ies))
|
||||
print(
|
||||
" {:20} {:30} {:3} {:30}".format(
|
||||
p.get_hw_address(), p.get_name(), p.get_strength(), ies
|
||||
)
|
||||
)
|
||||
print("")
|
||||
|
||||
# Connect to first peer
|
||||
profile = create_profile('P2P-connection', peers[0].get_hw_address())
|
||||
client.add_and_activate_connection2(profile,
|
||||
device,
|
||||
"/",
|
||||
GLib.Variant('a{sv}', {}),
|
||||
None,
|
||||
activated_cb,
|
||||
None)
|
||||
print(" * Connecting to peer {} using profile '{}'".format(peers[0].get_hw_address(),
|
||||
profile.get_id()))
|
||||
profile = create_profile("P2P-connection", peers[0].get_hw_address())
|
||||
client.add_and_activate_connection2(
|
||||
profile, device, "/", GLib.Variant("a{sv}", {}), None, activated_cb, None
|
||||
)
|
||||
print(
|
||||
" * Connecting to peer {} using profile '{}'".format(
|
||||
peers[0].get_hw_address(), profile.get_id()
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def start_find_cb(device, async_result, user_data):
|
||||
try:
|
||||
@@ -87,9 +94,10 @@ def start_find_cb(device, async_result, user_data):
|
||||
sys.stderr.write("Error: %s\n" % e)
|
||||
main_loop.quit()
|
||||
|
||||
print(" * Scanning on device {}...".format(device.get_iface()));
|
||||
print(" * Scanning on device {}...".format(device.get_iface()))
|
||||
GLib.timeout_add(10000, scan_timeout_cb, device)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
client = NM.Client.new(None)
|
||||
device = None
|
||||
@@ -103,7 +111,7 @@ if __name__ == "__main__":
|
||||
if device is None:
|
||||
sys.exit("No Wi-Fi P2P device found")
|
||||
|
||||
device.start_find(GLib.Variant('a{sv}', {}), None, start_find_cb, None)
|
||||
device.start_find(GLib.Variant("a{sv}", {}), None, start_find_cb, None)
|
||||
|
||||
main_loop = GLib.MainLoop()
|
||||
main_loop.run()
|
||||
|
@@ -6,11 +6,13 @@ import dbus
|
||||
import dbus.service
|
||||
import dbus.mainloop.glib
|
||||
|
||||
IFACE_SECRET_AGENT = 'org.freedesktop.NetworkManager.SecretAgent'
|
||||
IFACE_AGENT_MANAGER = 'org.freedesktop.NetworkManager.AgentManager'
|
||||
IFACE_SECRET_AGENT = "org.freedesktop.NetworkManager.SecretAgent"
|
||||
IFACE_AGENT_MANAGER = "org.freedesktop.NetworkManager.AgentManager"
|
||||
|
||||
|
||||
class NotAuthorizedException(dbus.DBusException):
|
||||
_dbus_error_name = IFACE_SECRET_AGENT + '.NotAuthorized'
|
||||
_dbus_error_name = IFACE_SECRET_AGENT + ".NotAuthorized"
|
||||
|
||||
|
||||
class Agent(dbus.service.Object):
|
||||
def __init__(self, bus, object_path):
|
||||
@@ -18,41 +20,58 @@ class Agent(dbus.service.Object):
|
||||
self.bus = bus
|
||||
dbus.service.Object.__init__(self, bus, object_path)
|
||||
|
||||
@dbus.service.method(IFACE_SECRET_AGENT,
|
||||
in_signature='a{sa{sv}}osasb',
|
||||
out_signature='a{sa{sv}}',
|
||||
sender_keyword='sender')
|
||||
def GetSecrets(self, connection_hash, connection_path, setting_name, hints, request_new, sender=None):
|
||||
@dbus.service.method(
|
||||
IFACE_SECRET_AGENT,
|
||||
in_signature="a{sa{sv}}osasb",
|
||||
out_signature="a{sa{sv}}",
|
||||
sender_keyword="sender",
|
||||
)
|
||||
def GetSecrets(
|
||||
self,
|
||||
connection_hash,
|
||||
connection_path,
|
||||
setting_name,
|
||||
hints,
|
||||
request_new,
|
||||
sender=None,
|
||||
):
|
||||
if not sender:
|
||||
raise NotAuthorizedException("Internal error: couldn't get sender")
|
||||
uid = self.bus.get_unix_user(sender)
|
||||
if uid != 0:
|
||||
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
|
||||
s_gsm = dbus.Dictionary({'password': 'asdfadfasdfaf'})
|
||||
con = dbus.Dictionary({'gsm': s_gsm})
|
||||
s_gsm = dbus.Dictionary({"password": "asdfadfasdfaf"})
|
||||
con = dbus.Dictionary({"gsm": s_gsm})
|
||||
return con
|
||||
|
||||
|
||||
def register(proxy):
|
||||
proxy.Register("test.agent.id", dbus_interface=IFACE_AGENT_MANAGER)
|
||||
print("Registered!")
|
||||
return False
|
||||
|
||||
|
||||
def unregister(proxy, loop):
|
||||
proxy.Unregister(dbus_interface=IFACE_AGENT_MANAGER)
|
||||
loop.quit()
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
|
||||
|
||||
bus = dbus.SystemBus()
|
||||
obj = Agent(bus, "/org/freedesktop/NetworkManager/SecretAgent")
|
||||
proxy = bus.get_object("org.freedesktop.NetworkManager",
|
||||
"/org/freedesktop/NetworkManager/AgentManager")
|
||||
proxy = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/AgentManager"
|
||||
)
|
||||
|
||||
mainloop = GLib.MainLoop()
|
||||
|
||||
@@ -65,8 +84,8 @@ def main():
|
||||
pass
|
||||
|
||||
print("Unregistering...")
|
||||
unregister(proxy, mainloop);
|
||||
unregister(proxy, mainloop)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
@@ -6,56 +6,85 @@ import argparse
|
||||
|
||||
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
|
||||
parser.add_argument('--nm', dest='do_set_nm_logging', action='store',
|
||||
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.)')
|
||||
parser.add_argument(
|
||||
"--nm",
|
||||
dest="do_set_nm_logging",
|
||||
action="store",
|
||||
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
|
||||
parser.add_argument('--mm', dest='do_set_mm_logging', action='store',
|
||||
help='modify log level for ModemManager (debug, info, etc.)')
|
||||
parser.add_argument(
|
||||
"--mm",
|
||||
dest="do_set_mm_logging",
|
||||
action="store",
|
||||
help="modify log level for ModemManager (debug, info, etc.)",
|
||||
)
|
||||
|
||||
# wpasupplicant options
|
||||
parser.add_argument('--wpa', dest='do_set_wpa_logging', action='store',
|
||||
help='modify log level for wpasupplicant (debug, msgdump, info, etc.)')
|
||||
parser.add_argument(
|
||||
"--wpa",
|
||||
dest="do_set_wpa_logging",
|
||||
action="store",
|
||||
help="modify log level for wpasupplicant (debug, msgdump, info, etc.)",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.do_set_nm_logging:
|
||||
#print args.log_domains
|
||||
# print args.log_domains
|
||||
dom_msg = ""
|
||||
if args.log_domains:
|
||||
dom_msg = " for domains: " + ','.join(args.log_domains)
|
||||
print("Setting NetworkManager log level to '" + args.do_set_nm_logging + "'" + dom_msg)
|
||||
dom_msg = " for domains: " + ",".join(args.log_domains)
|
||||
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 = dbus.Interface(nm_bus, dbus_interface='org.freedesktop.NetworkManager')
|
||||
nm.SetLogging(args.do_set_nm_logging, ','.join(args.log_domains))
|
||||
nm_bus = bus.get_object(
|
||||
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager"
|
||||
)
|
||||
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:
|
||||
print("Setting ModemManager log level to '" + args.do_set_mm_logging + "'")
|
||||
|
||||
mm_bus = bus.get_object('org.freedesktop.ModemManager', '/org/freedesktop/ModemManager')
|
||||
mm = dbus.Interface(mm_bus, dbus_interface='org.freedesktop.ModemManager')
|
||||
mm_bus = bus.get_object(
|
||||
"org.freedesktop.ModemManager", "/org/freedesktop/ModemManager"
|
||||
)
|
||||
mm = dbus.Interface(mm_bus, dbus_interface="org.freedesktop.ModemManager")
|
||||
mm.SetLogging(args.do_set_mm_logging)
|
||||
|
||||
if 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")
|
||||
use_timestamps = dbus.Boolean(True, variant_level=1)
|
||||
else:
|
||||
print("Disabling timestamps for wpasupplicant debugging logs")
|
||||
use_timestamps = dbus.Boolean(False, variant_level=1)
|
||||
|
||||
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.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))
|
||||
|
||||
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.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),
|
||||
)
|
||||
|
@@ -8,171 +8,196 @@ from __future__ import print_function
|
||||
|
||||
import os
|
||||
import gi
|
||||
gi.require_version('GIRepository', '2.0')
|
||||
|
||||
gi.require_version("GIRepository", "2.0")
|
||||
from gi.repository import GIRepository
|
||||
import argparse, re, sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
try:
|
||||
libs = os.environ['LD_LIBRARY_PATH'].split(':')
|
||||
libs = os.environ["LD_LIBRARY_PATH"].split(":")
|
||||
libs.reverse()
|
||||
for lib in libs:
|
||||
GIRepository.Repository.prepend_library_path(lib)
|
||||
except AttributeError:
|
||||
# An old GI version, that has no prepend_library_path
|
||||
# It's alright, it probably interprets LD_LIBRARY_PATH
|
||||
# correctly.
|
||||
pass
|
||||
# An old GI version, that has no prepend_library_path
|
||||
# It's alright, it probably interprets LD_LIBRARY_PATH
|
||||
# correctly.
|
||||
pass
|
||||
except KeyError:
|
||||
pass
|
||||
pass
|
||||
|
||||
gi.require_version('NM', '1.0')
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import NM, GObject
|
||||
|
||||
dbus_type_name_map = {
|
||||
'b': 'boolean',
|
||||
's': 'string',
|
||||
'i': 'int32',
|
||||
'u': 'uint32',
|
||||
't': 'uint64',
|
||||
'x': 'int64',
|
||||
'y': 'byte',
|
||||
'as': 'array of string',
|
||||
'au': 'array of uint32',
|
||||
'ay': 'byte array',
|
||||
'a{ss}': 'dict of string to string',
|
||||
'a{sv}': 'vardict',
|
||||
'aa{sv}': 'array of vardict',
|
||||
'aau': 'array of array of uint32',
|
||||
'aay': 'array of byte array',
|
||||
'a(ayuay)': 'array of legacy IPv6 address struct',
|
||||
'a(ayuayu)': 'array of legacy IPv6 route struct',
|
||||
"b": "boolean",
|
||||
"s": "string",
|
||||
"i": "int32",
|
||||
"u": "uint32",
|
||||
"t": "uint64",
|
||||
"x": "int64",
|
||||
"y": "byte",
|
||||
"as": "array of string",
|
||||
"au": "array of uint32",
|
||||
"ay": "byte array",
|
||||
"a{ss}": "dict of string to string",
|
||||
"a{sv}": "vardict",
|
||||
"aa{sv}": "array of vardict",
|
||||
"aau": "array of array of uint32",
|
||||
"aay": "array of byte array",
|
||||
"a(ayuay)": "array of legacy IPv6 address struct",
|
||||
"a(ayuayu)": "array of legacy IPv6 route struct",
|
||||
}
|
||||
|
||||
ns_map = {
|
||||
'c': 'http://www.gtk.org/introspection/c/1.0',
|
||||
'gi': 'http://www.gtk.org/introspection/core/1.0',
|
||||
'glib': 'http://www.gtk.org/introspection/glib/1.0'
|
||||
"c": "http://www.gtk.org/introspection/c/1.0",
|
||||
"gi": "http://www.gtk.org/introspection/core/1.0",
|
||||
"glib": "http://www.gtk.org/introspection/glib/1.0",
|
||||
}
|
||||
identifier_key = '{%s}identifier' % ns_map['c']
|
||||
nick_key = '{%s}nick' % ns_map['glib']
|
||||
symbol_prefix_key = '{%s}symbol-prefix' % ns_map['c']
|
||||
identifier_key = "{%s}identifier" % ns_map["c"]
|
||||
nick_key = "{%s}nick" % ns_map["glib"]
|
||||
symbol_prefix_key = "{%s}symbol-prefix" % ns_map["c"]
|
||||
|
||||
constants = {
|
||||
'TRUE': 'TRUE',
|
||||
'FALSE': 'FALSE',
|
||||
'G_MAXUINT32': 'G_MAXUINT32',
|
||||
'NULL': 'NULL' }
|
||||
"TRUE": "TRUE",
|
||||
"FALSE": "FALSE",
|
||||
"G_MAXUINT32": "G_MAXUINT32",
|
||||
"NULL": "NULL",
|
||||
}
|
||||
setting_names = {}
|
||||
|
||||
|
||||
def get_setting_name_define(setting):
|
||||
n = setting.attrib[symbol_prefix_key]
|
||||
if n and n.startswith("setting_"):
|
||||
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):
|
||||
for const in girxml.findall('./gi:namespace/gi:constant', ns_map):
|
||||
cname = const.attrib['{%s}type' % ns_map['c']]
|
||||
cvalue = const.attrib['value']
|
||||
for const in girxml.findall("./gi:namespace/gi:constant", ns_map):
|
||||
cname = const.attrib["{%s}type" % ns_map["c"]]
|
||||
cvalue = const.attrib["value"]
|
||||
if const.find('./gi:type[@name="utf8"]', ns_map) is not None:
|
||||
cvalue = '"%s"' % cvalue
|
||||
constants[cname] = cvalue
|
||||
|
||||
for enum in girxml.findall('./gi:namespace/gi:enumeration', ns_map):
|
||||
for enumval in enum.findall('./gi:member', ns_map):
|
||||
for enum in girxml.findall("./gi:namespace/gi:enumeration", ns_map):
|
||||
for enumval in enum.findall("./gi:member", ns_map):
|
||||
cname = enumval.attrib[identifier_key]
|
||||
cvalue = '%s (%s)' % (cname, enumval.attrib['value'])
|
||||
cvalue = "%s (%s)" % (cname, enumval.attrib["value"])
|
||||
constants[cname] = cvalue
|
||||
|
||||
for enum in girxml.findall('./gi:namespace/gi:bitfield', ns_map):
|
||||
for enumval in enum.findall('./gi:member', ns_map):
|
||||
for enum in girxml.findall("./gi:namespace/gi:bitfield", ns_map):
|
||||
for enumval in enum.findall("./gi:member", ns_map):
|
||||
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
|
||||
|
||||
for setting in settings:
|
||||
setting_type_name = 'NM' + setting.attrib['name'];
|
||||
setting_name_symbol = 'NM_SETTING_' + get_setting_name_define(setting) + '_SETTING_NAME'
|
||||
setting_type_name = "NM" + setting.attrib["name"]
|
||||
setting_name_symbol = (
|
||||
"NM_SETTING_" + get_setting_name_define(setting) + "_SETTING_NAME"
|
||||
)
|
||||
if setting_name_symbol in constants:
|
||||
setting_name = constants[setting_name_symbol]
|
||||
setting_names[setting_type_name] = setting_name
|
||||
|
||||
|
||||
def get_prop_type(setting, pspec):
|
||||
dbus_type = setting.get_dbus_property_type(pspec.name).dup_string()
|
||||
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)
|
||||
|
||||
return prop_type
|
||||
|
||||
|
||||
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:
|
||||
return None
|
||||
|
||||
doc = doc_xml.text
|
||||
if 'deprecated' in propxml.attrib:
|
||||
doc = doc + ' Deprecated: ' + propxml.attrib['deprecated']
|
||||
if "deprecated" in propxml.attrib:
|
||||
doc = doc + " Deprecated: " + propxml.attrib["deprecated"]
|
||||
|
||||
doc = re.sub(r'\n\s*', r' ', doc)
|
||||
doc = re.sub(r"\n\s*", r" ", doc)
|
||||
|
||||
# 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"
|
||||
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
|
||||
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
|
||||
doc = doc.replace('%%', '%')
|
||||
doc = doc.replace('<!-- -->', '')
|
||||
doc = re.sub(r' Element-.ype:.*', '', doc)
|
||||
doc = re.sub(r'#([A-Z]\w*)', r'\1', doc)
|
||||
doc = doc.replace("%%", "%")
|
||||
doc = doc.replace("<!-- -->", "")
|
||||
doc = re.sub(r" Element-.ype:.*", "", doc)
|
||||
doc = re.sub(r"#([A-Z]\w*)", r"\1", doc)
|
||||
|
||||
# Remove sentences that refer to functions
|
||||
doc = re.sub(r'\.\s+[^.]*\w\(\)[^.]*\.', r'.', doc)
|
||||
doc = re.sub(r"\.\s+[^.]*\w\(\)[^.]*\.", r".", doc)
|
||||
|
||||
return doc
|
||||
|
||||
|
||||
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:
|
||||
return default_value
|
||||
|
||||
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
|
||||
elif value_type == 'boolean':
|
||||
elif value_type == "boolean":
|
||||
default_value = str(default_value).upper()
|
||||
elif value_type == 'byte array':
|
||||
default_value = '[]'
|
||||
elif str(default_value).startswith('<'):
|
||||
elif value_type == "byte array":
|
||||
default_value = "[]"
|
||||
elif str(default_value).startswith("<"):
|
||||
default_value = None
|
||||
elif str(default_value).startswith('['):
|
||||
elif str(default_value).startswith("["):
|
||||
default_value = None
|
||||
|
||||
return default_value
|
||||
|
||||
|
||||
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
|
||||
return (x_prefix != "setting_connection", x_prefix);
|
||||
return (x_prefix != "setting_connection", x_prefix)
|
||||
|
||||
|
||||
def escape(val):
|
||||
return str(val).replace('"', '"')
|
||||
return str(val).replace('"', """)
|
||||
|
||||
|
||||
def usage():
|
||||
print("Usage: %s --gir FILE --output FILE" % sys.argv[0])
|
||||
exit()
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-l', '--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')
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--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()
|
||||
if args.gir is None or args.output is None:
|
||||
@@ -183,37 +208,50 @@ if args.lib_path:
|
||||
GIRepository.Repository.prepend_library_path(lib)
|
||||
|
||||
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)
|
||||
settings = girxml.findall('./gi:namespace/gi:class[@parent="Setting"]', ns_map)
|
||||
# Hack. Need a better way to do this
|
||||
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)
|
||||
|
||||
init_constants(girxml, settings)
|
||||
|
||||
outfile.write("""<?xml version=\"1.0\"?>
|
||||
outfile.write(
|
||||
"""<?xml version=\"1.0\"?>
|
||||
<!DOCTYPE nm-setting-docs [
|
||||
<!ENTITY quot """>
|
||||
]>
|
||||
<nm-setting-docs>
|
||||
""")
|
||||
"""
|
||||
)
|
||||
|
||||
for settingxml in settings:
|
||||
if 'abstract' in settingxml.attrib:
|
||||
if "abstract" in settingxml.attrib:
|
||||
continue
|
||||
|
||||
new_func = NM.__getattr__(settingxml.attrib['name'])
|
||||
new_func = NM.__getattr__(settingxml.attrib["name"])
|
||||
setting = new_func()
|
||||
|
||||
class_desc = get_docs(settingxml)
|
||||
if class_desc is None:
|
||||
raise Exception("%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)))
|
||||
raise Exception(
|
||||
"%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):
|
||||
pspec = setting_properties[prop]
|
||||
@@ -228,17 +266,21 @@ for settingxml in settings:
|
||||
value_desc = get_docs(propxml)
|
||||
default_value = get_default_value(setting, pspec, propxml)
|
||||
|
||||
prop_upper = prop.upper().replace('-', '_')
|
||||
prop_upper = prop.upper().replace("-", "_")
|
||||
|
||||
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:
|
||||
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" %
|
||||
(prop, prop_upper, value_type, default_value_as_xml, escape(value_desc)))
|
||||
outfile.write(
|
||||
' <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")
|
||||
|
||||
|
@@ -61,28 +61,33 @@ _setting_name_order = [
|
||||
"wpan",
|
||||
]
|
||||
|
||||
|
||||
def _setting_name_order_idx(name):
|
||||
try:
|
||||
return _setting_name_order.index(name)
|
||||
except ValueError:
|
||||
return len(_setting_name_order)
|
||||
|
||||
|
||||
def key_fcn_setting_name(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()])
|
||||
return sorted(keys, key = key)
|
||||
return sorted(keys, key=key)
|
||||
|
||||
|
||||
def node_to_dict(node, tag, key_attr):
|
||||
dictionary = collections.OrderedDict()
|
||||
if node is not None:
|
||||
for n in node.iter(tag):
|
||||
k = n.get(key_attr)
|
||||
assert(k is not None)
|
||||
assert k is not None
|
||||
dictionary[k] = n
|
||||
return dictionary
|
||||
|
||||
|
||||
def node_get_attr(nodes, name):
|
||||
for n in nodes:
|
||||
if n is None:
|
||||
@@ -92,18 +97,20 @@ def node_get_attr(nodes, name):
|
||||
return x
|
||||
return None
|
||||
|
||||
|
||||
def node_set_attr(dst_node, name, nodes):
|
||||
x = node_get_attr(nodes, name)
|
||||
if x:
|
||||
dst_node.set(name, x)
|
||||
|
||||
|
||||
###############################################################################
|
||||
|
||||
gl_only_from_first = False
|
||||
|
||||
argv = list(sys.argv[1:])
|
||||
while True:
|
||||
if argv[0] == '--only-from-first':
|
||||
if argv[0] == "--only-from-first":
|
||||
gl_only_from_first = True
|
||||
del argv[0]
|
||||
continue
|
||||
@@ -119,54 +126,51 @@ gl_input_files = list(argv[1:])
|
||||
|
||||
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):
|
||||
|
||||
settings = list([d.get(setting_name) for d in settings_roots])
|
||||
|
||||
if gl_only_from_first \
|
||||
and settings[0] is None:
|
||||
if gl_only_from_first and settings[0] is None:
|
||||
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 \
|
||||
and not properties[0]:
|
||||
if gl_only_from_first and not properties[0]:
|
||||
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, 'name_upper', settings)
|
||||
node_set_attr(setting_node, 'alias', settings)
|
||||
node_set_attr(setting_node, "description", settings)
|
||||
node_set_attr(setting_node, "name_upper", settings)
|
||||
node_set_attr(setting_node, "alias", settings)
|
||||
|
||||
for property_name in iter_keys_of_dicts(properties):
|
||||
|
||||
properties_attrs = list([p.get(property_name) for p in properties])
|
||||
|
||||
if gl_only_from_first \
|
||||
and properties_attrs[0] is None:
|
||||
if gl_only_from_first and properties_attrs[0] is None:
|
||||
continue
|
||||
|
||||
property_node = ET.SubElement(setting_node, 'property')
|
||||
property_node.set('name', property_name)
|
||||
property_node.set('name_upper', property_name.upper().replace('-', '_'))
|
||||
property_node = ET.SubElement(setting_node, "property")
|
||||
property_node.set("name", property_name)
|
||||
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:
|
||||
property_node.set('type', x)
|
||||
property_node.set("type", x)
|
||||
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, 'description', properties_attrs)
|
||||
node_set_attr(property_node, 'alias', properties_attrs)
|
||||
node_set_attr(property_node, "default", properties_attrs)
|
||||
node_set_attr(property_node, "description", properties_attrs)
|
||||
node_set_attr(property_node, "alias", properties_attrs)
|
||||
|
||||
ET.ElementTree(root_node).write(gl_output_xml_file)
|
||||
|
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user