all: reformat python files with python black

Part of !537.

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

View File

@@ -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)

View File

@@ -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)

View File

@@ -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)

View File

@@ -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)

View File

@@ -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:

View File

@@ -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)

View File

@@ -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()

View File

@@ -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")

View File

@@ -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")

View File

@@ -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()

View File

@@ -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)

View File

@@ -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()))

View File

@@ -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)

View File

@@ -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)

View File

@@ -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])

View File

@@ -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()

View File

@@ -31,7 +31,9 @@ devpath = nm.GetDeviceByIpIface(iface)
# Get a proxy to the wifi device and get the active access point's object path
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)

View File

@@ -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)