././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1610805591.490605 python-networkmanager-2.2/0000755000175100001640000000000000000000000015262 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/COPYING0000644000175100001640000000166700000000000016327 0ustar00runnerdockerpython-networkmanager - Easy communication with NetworkManager Copyright (C) 2011-2021 Dennis Kaarsemaker This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/MANIFEST.in0000644000175100001640000000014500000000000017020 0ustar00runnerdockerinclude docs/index.rst include docs/Makefile include docs/conf.py include examples/* include COPYING ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/NetworkManager.py0000644000175100001640000013404100000000000020563 0ustar00runnerdocker# NetworkManager - a library to make interacting with the NetworkManager daemon # easier. # # (C)2011-2021 Dennis Kaarsemaker # License: zlib import copy import dbus import dbus.service import os import six import socket import struct import sys import time import warnings import weakref import xml.etree.ElementTree as etree class ObjectVanished(Exception): def __init__(self, obj): self.obj = obj super(ObjectVanished, self).__init__(obj.object_path) class SignalDispatcher(object): def __init__(self): self.handlers = {} self.args = {} self.interfaces = set() self.setup = False def setup_signals(self): if not self.setup: bus = dbus.SystemBus() for interface in self.interfaces: bus.add_signal_receiver(self.handle_signal, dbus_interface=interface, interface_keyword='interface', member_keyword='signal', path_keyword='path') self.setup = True self.listen_for_restarts() def listen_for_restarts(self): # If we have a mainloop, listen for disconnections if not NMDbusInterface.last_disconnect and dbus.get_default_main_loop(): dbus.SystemBus().add_signal_receiver(self.handle_restart, 'NameOwnerChanged', 'org.freedesktop.DBus') NMDbusInterface.last_disconnect = 1 def add_signal_receiver(self, interface, signal, obj, func, args, kwargs): self.setup_signals() key = (interface, signal) if key not in self.handlers: self.handlers[key] = [] self.handlers[key].append((obj, func, args, kwargs)) def handle_signal(self, *args, **kwargs): key = (kwargs['interface'], kwargs['signal']) skwargs = {} sargs = [] if key not in self.handlers: return try: sender = fixups.base_to_python(kwargs['path']) for arg, (name, signature) in zip(args, self.args[key]): if name: skwargs[name] = fixups.to_python(type(sender).__name__, kwargs['signal'], name, arg, signature) else: # Older NetworkManager versions don't supply attribute names. Hope for the best. sargs.append(fixups.to_python(type(sender).__name__, kwargs['signal'], None, arg, signature)) except dbus.exceptions.DBusException: # This happens if the sender went away. Tough luck, no signal for you. return to_delete = [] for pos, (match, receiver, rargs, rkwargs) in enumerate(self.handlers[key]): try: match == sender except ObjectVanished: to_delete.append(pos) continue if match == sender: rkwargs['interface'] = kwargs['interface'] rkwargs['signal'] = kwargs['signal'] rkwargs.update(skwargs) receiver(sender, *(sargs + rargs), **rkwargs) for pos in reversed(to_delete): self.handlers[key].pop(pos) def handle_restart(self, name, old, new): if str(new) == "" or str(name) != 'org.freedesktop.NetworkManager': return NMDbusInterface.last_disconnect = time.time() time.sleep(1) # Give NetworkManager a bit of time to start and rediscover itself. for key in self.handlers: val, self.handlers[key] = self.handlers[key], [] for obj, func, args, kwargs in val: try: # This resets the object path if needed obj.proxy self.add_signal_receiver(key[0], key[1], obj, func, args, kwargs) except ObjectVanished: pass SignalDispatcher = SignalDispatcher() # We completely dynamically generate all classes using introspection data. As # this is done at import time, use a special dbus connection that does not get # in the way of setting a mainloop and doing async stuff later. init_bus = dbus.SystemBus(private=True) xml_cache = {} class NMDbusInterfaceType(type): """Metaclass that generates our classes based on introspection data""" dbus_service = 'org.freedesktop.NetworkManager' def __new__(type_, name, bases, attrs): attrs['dbus_service'] = type_.dbus_service attrs['properties'] = [] attrs['introspection_data'] = None attrs['signals'] = [] # Derive the interface name from the name of the class, but let classes # override it if needed if 'interface_names' not in attrs and 'NMDbusInterface' not in name: attrs['interface_names'] = ['org.freedesktop.NetworkManager.%s' % name] for base in bases: if hasattr(base, 'interface_names'): attrs['interface_names'] = ['%s.%s' % (base.interface_names[0], name)] + base.interface_names break else: for base in bases: if hasattr(base, 'interface_names'): attrs['interface_names'] += base.interface_names break if 'interface_names' in attrs: SignalDispatcher.interfaces.update(attrs['interface_names']) # If we know where to find this object, let's introspect it and # generate properties and methods if 'object_path' in attrs and attrs['object_path']: proxy = init_bus.get_object(type_.dbus_service, attrs['object_path']) attrs['introspection_data'] = proxy.Introspect(dbus_interface='org.freedesktop.DBus.Introspectable') root = etree.fromstring(attrs['introspection_data']) for element in root: if element.tag == 'interface' and element.attrib['name'] in attrs['interface_names']: for item in element: if item.tag == 'property': attrs[item.attrib['name']] = type_.make_property(name, element.attrib['name'], item.attrib) attrs['properties'].append(item.attrib['name']) elif item.tag == 'method': aname = item.attrib['name'] if aname in attrs: aname = '_' + aname attrs[aname] = type_.make_method(name, element.attrib['name'], item.attrib, list(item)) elif item.tag == 'signal': SignalDispatcher.args[(element.attrib['name'], item.attrib['name'])] = [(arg.attrib.get('name',None), arg.attrib['type']) for arg in item] attrs['On' + item.attrib['name']] = type_.make_signal(name, element.attrib['name'], item.attrib) attrs['signals'].append(item.attrib['name']) klass = super(NMDbusInterfaceType, type_).__new__(type_, name, bases, attrs) return klass @staticmethod def make_property(klass, interface, attrib): name = attrib['name'] def get_func(self): try: data = self.proxy.Get(interface, name, dbus_interface='org.freedesktop.DBus.Properties') except dbus.exceptions.DBusException as e: if e.get_dbus_name() == 'org.freedesktop.DBus.Error.UnknownMethod': raise ObjectVanished(self) raise return fixups.to_python(klass, 'Get', name, data, attrib['type']) if attrib['access'] == 'read': return property(get_func) def set_func(self, value): value = fixups.to_dbus(klass, 'Set', name, value, attrib['type']) try: return self.proxy.Set(interface, name, value, dbus_interface='org.freedesktop.DBus.Properties') except dbus.exceptions.DBusException as e: if e.get_dbus_name() == 'org.freedesktop.DBus.Error.UnknownMethod': raise ObjectVanished(self) raise return property(get_func, set_func) @staticmethod def make_method(klass, interface, attrib, args): name = attrib['name'] outargs = [x for x in args if x.tag == 'arg' and x.attrib['direction'] == 'out'] outargstr = ', '.join([x.attrib['name'] for x in outargs]) or 'ret' args = [x for x in args if x.tag == 'arg' and x.attrib['direction'] == 'in'] argstr = ', '.join([x.attrib['name'] for x in args]) ret = {} code = "def %s(self%s):\n" % (name, ', ' + argstr if argstr else '') for arg in args: argname = arg.attrib['name'] signature = arg.attrib['type'] code += " %s = fixups.to_dbus('%s', '%s', '%s', %s, '%s')\n" % (argname, klass, name, argname, argname, signature) code += " try:\n" code += " %s = dbus.Interface(self.proxy, '%s').%s(%s)\n" % (outargstr, interface, name, argstr) code += " except dbus.exceptions.DBusException as e:\n" code += " if e.get_dbus_name() == 'org.freedesktop.DBus.Error.UnknownMethod':\n" code += " raise ObjectVanished(self)\n" code += " raise\n" for arg in outargs: argname = arg.attrib['name'] signature = arg.attrib['type'] code += " %s = fixups.to_python('%s', '%s', '%s', %s, '%s')\n" % (argname, klass, name, argname, argname, signature) code += " return (%s)" % outargstr exec(code, globals(), ret) return ret[name] @staticmethod def make_signal(klass, interface, attrib): name = attrib['name'] ret = {} code = "def On%s(self, func, *args, **kwargs):" % name code += " SignalDispatcher.add_signal_receiver('%s', '%s', self, func, list(args), kwargs)" % (interface, name) exec(code, globals(), ret) return ret['On' + name] @six.add_metaclass(NMDbusInterfaceType) class NMDbusInterface(object): object_path = None last_disconnect = 0 is_transient = False def __new__(klass, object_path=None): # If we didn't introspect this one at definition time, let's do it now. if object_path and not klass.introspection_data: proxy = dbus.SystemBus().get_object(klass.dbus_service, object_path) klass.introspection_data = proxy.Introspect(dbus_interface='org.freedesktop.DBus.Introspectable') root = etree.fromstring(klass.introspection_data) for element in root: if element.tag == 'interface' and element.attrib['name'] in klass.interface_names: for item in element: if item.tag == 'property': setattr(klass, item.attrib['name'], type(klass).make_property(klass.__name__, element.attrib['name'], item.attrib)) klass.properties.append(item.attrib['name']) elif item.tag == 'method': aname = item.attrib['name'] if hasattr(klass, aname): aname = '_' + aname setattr(klass, aname, type(klass).make_method(klass.__name__, element.attrib['name'], item.attrib, list(item))) elif item.tag == 'signal': SignalDispatcher.args[(element.attrib['name'], item.attrib['name'])] = [(arg.attrib.get('name',None), arg.attrib['type']) for arg in item] setattr(klass, 'On' + item.attrib['name'], type(klass).make_signal(klass.__name__, element.attrib['name'], item.attrib)) klass.signals.append(item.attrib['name']) SignalDispatcher.listen_for_restarts() return super(NMDbusInterface, klass).__new__(klass) def __init__(self, object_path=None): if isinstance(object_path, NMDbusInterface): object_path = object_path.object_path self.object_path = self.object_path or object_path self._proxy = None def __eq__(self, other): return isinstance(other, NMDbusInterface) and self.object_path and other.object_path == self.object_path @property def proxy(self): if not self._proxy: self._proxy = dbus.SystemBus().get_object(self.dbus_service, self.object_path, follow_name_owner_changes=True) self._proxy.created = time.time() elif self._proxy.created < self.last_disconnect: if self.is_transient: raise ObjectVanished(self) obj = type(self)(self.object_path) if obj.object_path != self.object_path: self.object_path = obj.object_path self._proxy = dbus.SystemBus().get_object(self.dbus_service, self.object_path) self._proxy.created = time.time() return self._proxy # Backwards compatibility interface def connect_to_signal(self, signal, handler, *args, **kwargs): return getattr(self, 'On' + signal)(handler, *args, **kwargs) class TransientNMDbusInterface(NMDbusInterface): is_transient = True class NetworkManager(NMDbusInterface): interface_names = ['org.freedesktop.NetworkManager'] object_path = '/org/freedesktop/NetworkManager' # noop method for backward compatibility. It is no longer necessary to call # this but let's not break code that does so. def auto_reconnect(self): pass class Statistics(NMDbusInterface): object_path = '/org/freedesktop/NetworkManager/Statistics' class Settings(NMDbusInterface): object_path = '/org/freedesktop/NetworkManager/Settings' class AgentManager(NMDbusInterface): object_path = '/org/freedesktop/NetworkManager/AgentManager' class Connection(NMDbusInterface): interface_names = ['org.freedesktop.NetworkManager.Settings.Connection'] has_secrets = ['802-1x', '802-11-wireless-security', 'cdma', 'gsm', 'pppoe', 'vpn'] def __init__(self, object_path): super(Connection, self).__init__(object_path) self.uuid = self.GetSettings()['connection']['uuid'] def GetSecrets(self, name=None): settings = self.GetSettings() if name is None: name = settings['connection']['type'] name = settings[name].get('security', name) try: return self._GetSecrets(name) except dbus.exceptions.DBusException as e: if e.get_dbus_name() != 'org.freedesktop.NetworkManager.AgentManager.NoSecrets': raise return {key: {} for key in settings} @staticmethod def all(): return Settings.ListConnections() def __eq__(self, other): return isinstance(other, type(self)) and self.uuid == other.uuid class ActiveConnection(TransientNMDbusInterface): interface_names = ['org.freedesktop.NetworkManager.Connection.Active'] def __new__(klass, object_path): if klass == ActiveConnection: # Automatically turn this into a VPNConnection if needed obj = dbus.SystemBus().get_object(klass.dbus_service, object_path) if obj.Get('org.freedesktop.NetworkManager.Connection.Active', 'Vpn', dbus_interface='org.freedesktop.DBus.Properties'): return VPNConnection.__new__(VPNConnection, object_path) return super(ActiveConnection, klass).__new__(klass, object_path) def __eq__(self, other): return isinstance(other, type(self)) and self.Uuid == other.Uuid class VPNConnection(ActiveConnection): interface_names = ['org.freedesktop.NetworkManager.VPN.Connection'] class Device(NMDbusInterface): interface_names = ['org.freedesktop.NetworkManager.Device', 'org.freedesktop.NetworkManager.Device.Statistics'] def __new__(klass, object_path): if klass == Device: # Automatically specialize the device try: obj = dbus.SystemBus().get_object(klass.dbus_service, object_path) klass = device_class(obj.Get('org.freedesktop.NetworkManager.Device', 'DeviceType', dbus_interface='org.freedesktop.DBus.Properties')) return klass.__new__(klass, object_path) except ObjectVanished: pass return super(Device, klass).__new__(klass, object_path) @staticmethod def all(): return NetworkManager.Devices def __eq__(self, other): return isinstance(other, type(self)) and self.IpInterface == other.IpInterface # Backwards compatibility method. Devices now auto-specialize, so this is # no longer needed. But code may use it. def SpecificDevice(self): return self def device_class(typ): return { NM_DEVICE_TYPE_ADSL: Adsl, NM_DEVICE_TYPE_BOND: Bond, NM_DEVICE_TYPE_BRIDGE: Bridge, NM_DEVICE_TYPE_BT: Bluetooth, NM_DEVICE_TYPE_ETHERNET: Wired, NM_DEVICE_TYPE_GENERIC: Generic, NM_DEVICE_TYPE_INFINIBAND: Infiniband, NM_DEVICE_TYPE_IP_TUNNEL: IPTunnel, NM_DEVICE_TYPE_MACVLAN: Macvlan, NM_DEVICE_TYPE_MODEM: Modem, NM_DEVICE_TYPE_OLPC_MESH: OlpcMesh, NM_DEVICE_TYPE_TEAM: Team, NM_DEVICE_TYPE_TUN: Tun, NM_DEVICE_TYPE_VETH: Veth, NM_DEVICE_TYPE_VLAN: Vlan, NM_DEVICE_TYPE_VXLAN: Vxlan, NM_DEVICE_TYPE_WIFI: Wireless, NM_DEVICE_TYPE_WIMAX: Wimax, NM_DEVICE_TYPE_MACSEC: MacSec, NM_DEVICE_TYPE_DUMMY: Dummy, NM_DEVICE_TYPE_PPP: PPP, NM_DEVICE_TYPE_OVS_INTERFACE: OvsIf, NM_DEVICE_TYPE_OVS_PORT: OvsPort, NM_DEVICE_TYPE_OVS_BRIDGE: OvsBridge, NM_DEVICE_TYPE_WPAN: Wpan, NM_DEVICE_TYPE_6LOWPAN: SixLoWpan, NM_DEVICE_TYPE_WIREGUARD: WireGuard, NM_DEVICE_TYPE_VRF: Vrf, NM_DEVICE_TYPE_WIFI_P2P: WifiP2p, }[typ] class Adsl(Device): pass class Bluetooth(Device): pass class Bond(Device): pass class Bridge(Device): pass class Generic(Device): pass class Infiniband(Device): pass class IPTunnel(Device): pass class Macvlan(Device): pass class Modem(Device): pass class OlpcMesh(Device): pass class Team(Device): pass class Tun(Device): pass class Veth(Device): pass class Vlan(Device): pass class Vxlan(Device): pass class Wimax(Device): pass class Wired(Device): pass class Wireless(Device): pass class MacSec(Device): pass class Dummy(Device): pass class PPP(Device): pass class OvsIf(Device): pass class OvsPort(Device): pass class OvsBridge(Device): pass class Wpan(Device): pass class SixLoWpan(Device): pass class WireGuard(Device): pass class WifiP2p(Device): pass class Vrf(Device): pass class NSP(TransientNMDbusInterface): interface_names = ['org.freedesktop.NetworkManager.Wimax.NSP'] class AccessPoint(NMDbusInterface): @staticmethod def all(): for device in Device.all(): if isinstance(device, Wireless): for ap in device.AccessPoints: yield ap def __eq__(self, other): return isinstance(other, type(self)) and self.HwAddress == other.HwAddress class IP4Config(TransientNMDbusInterface): pass class IP6Config(TransientNMDbusInterface): pass class DHCP4Config(TransientNMDbusInterface): pass class DHCP6Config(TransientNMDbusInterface): pass # Evil hack to work around not being able to specify a method name in the # dbus.service.method decorator. class SecretAgentType(type(dbus.service.Object)): def __new__(type_, name, bases, attrs): if bases != (dbus.service.Object,): attrs['GetSecretsImpl'] = attrs.pop('GetSecrets') return super(SecretAgentType, type_).__new__(type_, name, bases, attrs) @six.add_metaclass(SecretAgentType) class SecretAgent(dbus.service.Object): object_path = '/org/freedesktop/NetworkManager/SecretAgent' interface_name = 'org.freedesktop.NetworkManager.SecretAgent' def __init__(self, identifier): self.identifier = identifier dbus.service.Object.__init__(self, dbus.SystemBus(), self.object_path) AgentManager.Register(self.identifier) @dbus.service.method(dbus_interface=interface_name, in_signature='a{sa{sv}}osasu', out_signature='a{sa{sv}}') def GetSecrets(self, connection, connection_path, setting_name, hints, flags): settings = fixups.to_python('SecretAgent', 'GetSecrets', 'connection', connection, 'a{sa{sv}}') connection = fixups.to_python('SecretAgent', 'GetSecrets', 'connection_path', connection_path, 'o') setting_name = fixups.to_python('SecretAgent', 'GetSecrets', 'setting_name', setting_name, 's') hints = fixups.to_python('SecretAgent', 'GetSecrets', 'hints', hints, 'as') return self.GetSecretsImpl(settings, connection, setting_name, hints, flags) # These two are interfaces that must be provided to NetworkManager. Keep them # as comments for documentation purposes. # # class PPP(NMDbusInterface): pass # class VPNPlugin(NMDbusInterface): # interface_names = ['org.freedesktop.NetworkManager.VPN.Plugin'] def const(prefix, val): prefix = 'NM_' + prefix.upper() + '_' for key, vval in globals().items(): if 'REASON' in key and 'REASON' not in prefix: continue if key.startswith(prefix) and val == vval: return key.replace(prefix,'').lower() raise ValueError("No constant found for %s* with value %d", (prefix, val)) # Several fixer methods to make the data easier to handle in python # - SSID sent/returned as bytes (only encoding tried is utf-8) # - IP, Mac address and route metric encoding/decoding class fixups(object): @staticmethod def to_dbus(klass, method, arg, val, signature): if arg in ('connection' 'properties') and signature == 'a{sa{sv}}': settings = copy.deepcopy(val) for key in settings: if 'mac-address' in settings[key]: settings[key]['mac-address'] = fixups.mac_to_dbus(settings[key]['mac-address']) if 'cloned-mac-address' in settings[key]: settings[key]['cloned-mac-address'] = fixups.mac_to_dbus(settings[key]['cloned-mac-address']) if 'bssid' in settings[key]: settings[key]['bssid'] = fixups.mac_to_dbus(settings[key]['bssid']) for cert in ['ca-cert', 'client-cert', 'phase2-ca-cert', 'phase2-client-cert', 'private-key']: if cert in settings[key]: settings[key][cert] = fixups.cert_to_dbus(settings[key][cert]) if 'ssid' in settings.get('802-11-wireless', {}): settings['802-11-wireless']['ssid'] = fixups.ssid_to_dbus(settings['802-11-wireless']['ssid']) if 'ipv4' in settings: if 'address-data' in settings['ipv4']: for item in settings['ipv4']['address-data']: item['prefix'] = dbus.UInt32(item['prefix']) settings['ipv4']['address-data'] = dbus.Array( settings['ipv4']['address-data'], signature=dbus.Signature('a{sv}')) if 'route-data' in settings['ipv4']: for item in settings['ipv4']['route-data']: item['prefix'] = dbus.UInt32(item['prefix']) settings['ipv4']['route-data'] = dbus.Array( settings['ipv4']['route-data'], signature=dbus.Signature('a{sv}')) if 'addresses' in settings['ipv4']: settings['ipv4']['addresses'] = [fixups.addrconf_to_dbus(addr,socket.AF_INET) for addr in settings['ipv4']['addresses']] if 'routes' in settings['ipv4']: settings['ipv4']['routes'] = [fixups.route_to_dbus(route,socket.AF_INET) for route in settings['ipv4']['routes']] if 'dns' in settings['ipv4']: settings['ipv4']['dns'] = [fixups.addr_to_dbus(addr,socket.AF_INET) for addr in settings['ipv4']['dns']] if 'ipv6' in settings: if 'address-data' in settings['ipv6']: for item in settings['ipv6']['address-data']: item['prefix'] = dbus.UInt32(item['prefix']) settings['ipv6']['address-data'] = dbus.Array( settings['ipv6']['address-data'], signature=dbus.Signature('a{sv}')) if 'route-data' in settings['ipv6']: for item in settings['ipv6']['route-data']: item['prefix'] = dbus.UInt32(item['prefix']) settings['ipv6']['route-data'] = dbus.Array( settings['ipv6']['route-data'], signature=dbus.Signature('a{sv}')) if 'addresses' in settings['ipv6']: settings['ipv6']['addresses'] = [fixups.addrconf_to_dbus(addr,socket.AF_INET6) for addr in settings['ipv6']['addresses']] if 'routes' in settings['ipv6']: settings['ipv6']['routes'] = [fixups.route_to_dbus(route,socket.AF_INET6) for route in settings['ipv6']['routes']] if 'dns' in settings['ipv6']: settings['ipv6']['dns'] = [fixups.addr_to_dbus(addr,socket.AF_INET6) for addr in settings['ipv6']['dns']] # Get rid of empty arrays/dicts. dbus barfs on them (can't guess # signatures), and if they were to get through, NetworkManager # ignores them anyway. for key in list(settings.keys()): if isinstance(settings[key], dict): for key2 in list(settings[key].keys()): if settings[key][key2] in ({}, []): del settings[key][key2] if settings[key] in ({}, []): del settings[key] val = settings return fixups.base_to_dbus(val) @staticmethod def base_to_dbus(val): if isinstance(val, NMDbusInterface): return val.object_path if hasattr(val.__class__, 'mro'): for klass in val.__class__.mro(): if klass.__module__ in ('dbus', '_dbus_bindings'): return val if hasattr(val, '__iter__') and not isinstance(val, six.string_types): if hasattr(val, 'items'): return dict([(x, fixups.base_to_dbus(y)) for x, y in val.items()]) else: return [fixups.base_to_dbus(x) for x in val] return val @staticmethod def to_python(klass, method, arg, val, signature): val = fixups.base_to_python(val) klass_af = {'IP4Config': socket.AF_INET, 'IP6Config': socket.AF_INET6}.get(klass, socket.AF_INET) if method == 'Get': if arg == 'Ip4Address': return fixups.addr_to_python(val, socket.AF_INET) if arg == 'Ip6Address': return fixups.addr_to_python(val, socket.AF_INET6) if arg == 'Ssid': return fixups.ssid_to_python(val) if arg == 'Strength': return fixups.strength_to_python(val) if arg == 'Addresses': return [fixups.addrconf_to_python(addr, klass_af) for addr in val] if arg == 'Routes': return [fixups.route_to_python(route, klass_af) for route in val] if arg in ('Nameservers', 'WinsServers'): return [fixups.addr_to_python(addr, klass_af) for addr in val] if arg == 'Options': for key in val: if key.startswith('requested_'): val[key] = bool(int(val[key])) elif val[key].isdigit(): val[key] = int(val[key]) elif key in ('domain_name_servers', 'ntp_servers', 'routers'): val[key] = val[key].split() return val if method == 'GetSettings': if 'ssid' in val.get('802-11-wireless', {}): val['802-11-wireless']['ssid'] = fixups.ssid_to_python(val['802-11-wireless']['ssid']) for key in val: val_ = val[key] if 'mac-address' in val_: val_['mac-address'] = fixups.mac_to_python(val_['mac-address']) if 'cloned-mac-address' in val_: val_['cloned-mac-address'] = fixups.mac_to_python(val_['cloned-mac-address']) if 'bssid' in val_: val_['bssid'] = fixups.mac_to_python(val_['bssid']) if 'ipv4' in val: val['ipv4']['addresses'] = [fixups.addrconf_to_python(addr,socket.AF_INET) for addr in val['ipv4']['addresses']] val['ipv4']['routes'] = [fixups.route_to_python(route,socket.AF_INET) for route in val['ipv4']['routes']] val['ipv4']['dns'] = [fixups.addr_to_python(addr,socket.AF_INET) for addr in val['ipv4']['dns']] if 'ipv6' in val: val['ipv6']['addresses'] = [fixups.addrconf_to_python(addr,socket.AF_INET6) for addr in val['ipv6']['addresses']] val['ipv6']['routes'] = [fixups.route_to_python(route,socket.AF_INET6) for route in val['ipv6']['routes']] val['ipv6']['dns'] = [fixups.addr_to_python(addr,socket.AF_INET6) for addr in val['ipv6']['dns']] return val if method == 'PropertiesChanged': for prop in val: val[prop] = fixups.to_python(klass, 'Get', prop, val[prop], None) return val @staticmethod def base_to_python(val): if isinstance(val, dbus.ByteArray): return "".join([str(x) for x in val]) if isinstance(val, (dbus.Array, list, tuple)): return [fixups.base_to_python(x) for x in val] if isinstance(val, (dbus.Dictionary, dict)): return dict([(fixups.base_to_python(x), fixups.base_to_python(y)) for x,y in val.items()]) if isinstance(val, dbus.ObjectPath): for obj in (NetworkManager, Settings, AgentManager): if val == obj.object_path: return obj if val.startswith('/org/freedesktop/NetworkManager/'): classname = val.split('/')[4] classname = { 'Settings': 'Connection', 'Devices': 'Device', }.get(classname, classname) return globals()[classname](val) if val == '/': return None if isinstance(val, (dbus.Signature, dbus.String)): return six.text_type(val) if isinstance(val, dbus.Boolean): return bool(val) if isinstance(val, (dbus.Int16, dbus.UInt16, dbus.Int32, dbus.UInt32, dbus.Int64, dbus.UInt64)): return int(val) if isinstance(val, dbus.Byte): return six.int2byte(int(val)) return val @staticmethod def ssid_to_python(ssid): try: return bytes().join(ssid).decode('utf-8') except UnicodeDecodeError: ssid = bytes().join(ssid).decode('utf-8', 'replace') warnings.warn("Unable to decode ssid %s properly" % ssid, UnicodeWarning) return ssid @staticmethod def ssid_to_dbus(ssid): if isinstance(ssid, six.text_type): ssid = ssid.encode('utf-8') return [dbus.Byte(x) for x in ssid] @staticmethod def strength_to_python(strength): return struct.unpack('B', strength)[0] @staticmethod def mac_to_python(mac): return "%02X:%02X:%02X:%02X:%02X:%02X" % tuple([ord(x) for x in mac]) @staticmethod def mac_to_dbus(mac): return [dbus.Byte(int(x, 16)) for x in mac.split(':')] @staticmethod def addrconf_to_python(addrconf,family): addr, netmask, gateway = addrconf return [ fixups.addr_to_python(addr,family), netmask, fixups.addr_to_python(gateway,family) ] @staticmethod def addrconf_to_dbus(addrconf,family): addr, netmask, gateway = addrconf if (family == socket.AF_INET): return [ fixups.addr_to_dbus(addr,family), fixups.mask_to_dbus(netmask), fixups.addr_to_dbus(gateway,family) ] else: return dbus.Struct( ( fixups.addr_to_dbus(addr,family), fixups.mask_to_dbus(netmask), fixups.addr_to_dbus(gateway,family) ), signature = 'ayuay' ) @staticmethod def addr_to_python(addr,family): if (family == socket.AF_INET): return socket.inet_ntop(family,struct.pack('I', addr)) else: return socket.inet_ntop(family,b''.join(addr)) @staticmethod def addr_to_dbus(addr,family): if (family == socket.AF_INET): return dbus.UInt32(struct.unpack('I', socket.inet_pton(family,addr))[0]) else: return dbus.ByteArray(socket.inet_pton(family,addr)) @staticmethod def mask_to_dbus(mask): return dbus.UInt32(mask) @staticmethod def route_to_python(route,family): addr, netmask, gateway, metric = route return [ fixups.addr_to_python(addr,family), netmask, fixups.addr_to_python(gateway,family), metric ] @staticmethod def route_to_dbus(route,family): addr, netmask, gateway, metric = route return [ fixups.addr_to_dbus(addr,family), fixups.mask_to_dbus(netmask), fixups.addr_to_dbus(gateway,family), metric ] @staticmethod def cert_to_dbus(cert): if not isinstance(cert, bytes): if not cert.startswith('file://'): cert = 'file://' + cert cert = cert.encode('utf-8') + b'\0' return [dbus.Byte(x) for x in cert] # Turn NetworkManager and Settings into singleton objects NetworkManager = NetworkManager() Settings = Settings() AgentManager = AgentManager() init_bus.close() del init_bus del xml_cache # Constants below are generated with makeconstants.py. Do not edit manually. NM_CAPABILITY_TEAM = 1 NM_CAPABILITY_OVS = 2 NM_STATE_UNKNOWN = 0 NM_STATE_ASLEEP = 10 NM_STATE_DISCONNECTED = 20 NM_STATE_DISCONNECTING = 30 NM_STATE_CONNECTING = 40 NM_STATE_CONNECTED_LOCAL = 50 NM_STATE_CONNECTED_SITE = 60 NM_STATE_CONNECTED_GLOBAL = 70 NM_CONNECTIVITY_UNKNOWN = 0 NM_CONNECTIVITY_NONE = 1 NM_CONNECTIVITY_PORTAL = 2 NM_CONNECTIVITY_LIMITED = 3 NM_CONNECTIVITY_FULL = 4 NM_DEVICE_TYPE_UNKNOWN = 0 NM_DEVICE_TYPE_ETHERNET = 1 NM_DEVICE_TYPE_WIFI = 2 NM_DEVICE_TYPE_UNUSED1 = 3 NM_DEVICE_TYPE_UNUSED2 = 4 NM_DEVICE_TYPE_BT = 5 NM_DEVICE_TYPE_OLPC_MESH = 6 NM_DEVICE_TYPE_WIMAX = 7 NM_DEVICE_TYPE_MODEM = 8 NM_DEVICE_TYPE_INFINIBAND = 9 NM_DEVICE_TYPE_BOND = 10 NM_DEVICE_TYPE_VLAN = 11 NM_DEVICE_TYPE_ADSL = 12 NM_DEVICE_TYPE_BRIDGE = 13 NM_DEVICE_TYPE_GENERIC = 14 NM_DEVICE_TYPE_TEAM = 15 NM_DEVICE_TYPE_TUN = 16 NM_DEVICE_TYPE_IP_TUNNEL = 17 NM_DEVICE_TYPE_MACVLAN = 18 NM_DEVICE_TYPE_VXLAN = 19 NM_DEVICE_TYPE_VETH = 20 NM_DEVICE_TYPE_MACSEC = 21 NM_DEVICE_TYPE_DUMMY = 22 NM_DEVICE_TYPE_PPP = 23 NM_DEVICE_TYPE_OVS_INTERFACE = 24 NM_DEVICE_TYPE_OVS_PORT = 25 NM_DEVICE_TYPE_OVS_BRIDGE = 26 NM_DEVICE_TYPE_WPAN = 27 NM_DEVICE_TYPE_6LOWPAN = 28 NM_DEVICE_TYPE_WIREGUARD = 29 NM_DEVICE_TYPE_WIFI_P2P = 30 NM_DEVICE_TYPE_VRF = 31 NM_DEVICE_CAP_NONE = 0 NM_DEVICE_CAP_NM_SUPPORTED = 1 NM_DEVICE_CAP_CARRIER_DETECT = 2 NM_DEVICE_CAP_IS_SOFTWARE = 4 NM_DEVICE_CAP_SRIOV = 8 NM_WIFI_DEVICE_CAP_NONE = 0 NM_WIFI_DEVICE_CAP_CIPHER_WEP40 = 1 NM_WIFI_DEVICE_CAP_CIPHER_WEP104 = 2 NM_WIFI_DEVICE_CAP_CIPHER_TKIP = 4 NM_WIFI_DEVICE_CAP_CIPHER_CCMP = 8 NM_WIFI_DEVICE_CAP_WPA = 16 NM_WIFI_DEVICE_CAP_RSN = 32 NM_WIFI_DEVICE_CAP_AP = 64 NM_WIFI_DEVICE_CAP_ADHOC = 128 NM_WIFI_DEVICE_CAP_FREQ_VALID = 256 NM_WIFI_DEVICE_CAP_FREQ_2GHZ = 512 NM_WIFI_DEVICE_CAP_FREQ_5GHZ = 1024 NM_WIFI_DEVICE_CAP_MESH = 4096 NM_WIFI_DEVICE_CAP_IBSS_RSN = 8192 NM_802_11_AP_FLAGS_NONE = 0 NM_802_11_AP_FLAGS_PRIVACY = 1 NM_802_11_AP_FLAGS_WPS = 2 NM_802_11_AP_FLAGS_WPS_PBC = 4 NM_802_11_AP_FLAGS_WPS_PIN = 8 NM_802_11_AP_SEC_NONE = 0 NM_802_11_AP_SEC_PAIR_WEP40 = 1 NM_802_11_AP_SEC_PAIR_WEP104 = 2 NM_802_11_AP_SEC_PAIR_TKIP = 4 NM_802_11_AP_SEC_PAIR_CCMP = 8 NM_802_11_AP_SEC_GROUP_WEP40 = 16 NM_802_11_AP_SEC_GROUP_WEP104 = 32 NM_802_11_AP_SEC_GROUP_TKIP = 64 NM_802_11_AP_SEC_GROUP_CCMP = 128 NM_802_11_AP_SEC_KEY_MGMT_PSK = 256 NM_802_11_AP_SEC_KEY_MGMT_802_1X = 512 NM_802_11_AP_SEC_KEY_MGMT_SAE = 1024 NM_802_11_AP_SEC_KEY_MGMT_OWE = 2048 NM_802_11_AP_SEC_KEY_MGMT_OWE_TM = 4096 NM_802_11_MODE_UNKNOWN = 0 NM_802_11_MODE_ADHOC = 1 NM_802_11_MODE_INFRA = 2 NM_802_11_MODE_AP = 3 NM_802_11_MODE_MESH = 4 NM_BT_CAPABILITY_NONE = 0 NM_BT_CAPABILITY_DUN = 1 NM_BT_CAPABILITY_NAP = 2 NM_DEVICE_MODEM_CAPABILITY_NONE = 0 NM_DEVICE_MODEM_CAPABILITY_POTS = 1 NM_DEVICE_MODEM_CAPABILITY_CDMA_EVDO = 2 NM_DEVICE_MODEM_CAPABILITY_GSM_UMTS = 4 NM_DEVICE_MODEM_CAPABILITY_LTE = 8 NM_WIMAX_NSP_NETWORK_TYPE_UNKNOWN = 0 NM_WIMAX_NSP_NETWORK_TYPE_HOME = 1 NM_WIMAX_NSP_NETWORK_TYPE_PARTNER = 2 NM_WIMAX_NSP_NETWORK_TYPE_ROAMING_PARTNER = 3 NM_DEVICE_STATE_UNKNOWN = 0 NM_DEVICE_STATE_UNMANAGED = 10 NM_DEVICE_STATE_UNAVAILABLE = 20 NM_DEVICE_STATE_DISCONNECTED = 30 NM_DEVICE_STATE_PREPARE = 40 NM_DEVICE_STATE_CONFIG = 50 NM_DEVICE_STATE_NEED_AUTH = 60 NM_DEVICE_STATE_IP_CONFIG = 70 NM_DEVICE_STATE_IP_CHECK = 80 NM_DEVICE_STATE_SECONDARIES = 90 NM_DEVICE_STATE_ACTIVATED = 100 NM_DEVICE_STATE_DEACTIVATING = 110 NM_DEVICE_STATE_FAILED = 120 NM_DEVICE_STATE_REASON_NONE = 0 NM_DEVICE_STATE_REASON_UNKNOWN = 1 NM_DEVICE_STATE_REASON_NOW_MANAGED = 2 NM_DEVICE_STATE_REASON_NOW_UNMANAGED = 3 NM_DEVICE_STATE_REASON_CONFIG_FAILED = 4 NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE = 5 NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED = 6 NM_DEVICE_STATE_REASON_NO_SECRETS = 7 NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT = 8 NM_DEVICE_STATE_REASON_SUPPLICANT_CONFIG_FAILED = 9 NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED = 10 NM_DEVICE_STATE_REASON_SUPPLICANT_TIMEOUT = 11 NM_DEVICE_STATE_REASON_PPP_START_FAILED = 12 NM_DEVICE_STATE_REASON_PPP_DISCONNECT = 13 NM_DEVICE_STATE_REASON_PPP_FAILED = 14 NM_DEVICE_STATE_REASON_DHCP_START_FAILED = 15 NM_DEVICE_STATE_REASON_DHCP_ERROR = 16 NM_DEVICE_STATE_REASON_DHCP_FAILED = 17 NM_DEVICE_STATE_REASON_SHARED_START_FAILED = 18 NM_DEVICE_STATE_REASON_SHARED_FAILED = 19 NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED = 20 NM_DEVICE_STATE_REASON_AUTOIP_ERROR = 21 NM_DEVICE_STATE_REASON_AUTOIP_FAILED = 22 NM_DEVICE_STATE_REASON_MODEM_BUSY = 23 NM_DEVICE_STATE_REASON_MODEM_NO_DIAL_TONE = 24 NM_DEVICE_STATE_REASON_MODEM_NO_CARRIER = 25 NM_DEVICE_STATE_REASON_MODEM_DIAL_TIMEOUT = 26 NM_DEVICE_STATE_REASON_MODEM_DIAL_FAILED = 27 NM_DEVICE_STATE_REASON_MODEM_INIT_FAILED = 28 NM_DEVICE_STATE_REASON_GSM_APN_FAILED = 29 NM_DEVICE_STATE_REASON_GSM_REGISTRATION_NOT_SEARCHING = 30 NM_DEVICE_STATE_REASON_GSM_REGISTRATION_DENIED = 31 NM_DEVICE_STATE_REASON_GSM_REGISTRATION_TIMEOUT = 32 NM_DEVICE_STATE_REASON_GSM_REGISTRATION_FAILED = 33 NM_DEVICE_STATE_REASON_GSM_PIN_CHECK_FAILED = 34 NM_DEVICE_STATE_REASON_FIRMWARE_MISSING = 35 NM_DEVICE_STATE_REASON_REMOVED = 36 NM_DEVICE_STATE_REASON_SLEEPING = 37 NM_DEVICE_STATE_REASON_CONNECTION_REMOVED = 38 NM_DEVICE_STATE_REASON_USER_REQUESTED = 39 NM_DEVICE_STATE_REASON_CARRIER = 40 NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED = 41 NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE = 42 NM_DEVICE_STATE_REASON_MODEM_NOT_FOUND = 43 NM_DEVICE_STATE_REASON_BT_FAILED = 44 NM_DEVICE_STATE_REASON_GSM_SIM_NOT_INSERTED = 45 NM_DEVICE_STATE_REASON_GSM_SIM_PIN_REQUIRED = 46 NM_DEVICE_STATE_REASON_GSM_SIM_PUK_REQUIRED = 47 NM_DEVICE_STATE_REASON_GSM_SIM_WRONG = 48 NM_DEVICE_STATE_REASON_INFINIBAND_MODE = 49 NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED = 50 NM_DEVICE_STATE_REASON_BR2684_FAILED = 51 NM_DEVICE_STATE_REASON_MODEM_MANAGER_UNAVAILABLE = 52 NM_DEVICE_STATE_REASON_SSID_NOT_FOUND = 53 NM_DEVICE_STATE_REASON_SECONDARY_CONNECTION_FAILED = 54 NM_DEVICE_STATE_REASON_DCB_FCOE_FAILED = 55 NM_DEVICE_STATE_REASON_TEAMD_CONTROL_FAILED = 56 NM_DEVICE_STATE_REASON_MODEM_FAILED = 57 NM_DEVICE_STATE_REASON_MODEM_AVAILABLE = 58 NM_DEVICE_STATE_REASON_SIM_PIN_INCORRECT = 59 NM_DEVICE_STATE_REASON_NEW_ACTIVATION = 60 NM_DEVICE_STATE_REASON_PARENT_CHANGED = 61 NM_DEVICE_STATE_REASON_PARENT_MANAGED_CHANGED = 62 NM_DEVICE_STATE_REASON_OVSDB_FAILED = 63 NM_DEVICE_STATE_REASON_IP_ADDRESS_DUPLICATE = 64 NM_DEVICE_STATE_REASON_IP_METHOD_UNSUPPORTED = 65 NM_DEVICE_STATE_REASON_SRIOV_CONFIGURATION_FAILED = 66 NM_DEVICE_STATE_REASON_PEER_NOT_FOUND = 67 NM_METERED_UNKNOWN = 0 NM_METERED_YES = 1 NM_METERED_NO = 2 NM_METERED_GUESS_YES = 3 NM_METERED_GUESS_NO = 4 NM_CONNECTION_MULTI_CONNECT_DEFAULT = 0 NM_CONNECTION_MULTI_CONNECT_SINGLE = 1 NM_CONNECTION_MULTI_CONNECT_MANUAL_MULTIPLE = 2 NM_CONNECTION_MULTI_CONNECT_MULTIPLE = 3 NM_ACTIVE_CONNECTION_STATE_UNKNOWN = 0 NM_ACTIVE_CONNECTION_STATE_ACTIVATING = 1 NM_ACTIVE_CONNECTION_STATE_ACTIVATED = 2 NM_ACTIVE_CONNECTION_STATE_DEACTIVATING = 3 NM_ACTIVE_CONNECTION_STATE_DEACTIVATED = 4 NM_ACTIVE_CONNECTION_STATE_REASON_UNKNOWN = 0 NM_ACTIVE_CONNECTION_STATE_REASON_NONE = 1 NM_ACTIVE_CONNECTION_STATE_REASON_USER_DISCONNECTED = 2 NM_ACTIVE_CONNECTION_STATE_REASON_DEVICE_DISCONNECTED = 3 NM_ACTIVE_CONNECTION_STATE_REASON_SERVICE_STOPPED = 4 NM_ACTIVE_CONNECTION_STATE_REASON_IP_CONFIG_INVALID = 5 NM_ACTIVE_CONNECTION_STATE_REASON_CONNECT_TIMEOUT = 6 NM_ACTIVE_CONNECTION_STATE_REASON_SERVICE_START_TIMEOUT = 7 NM_ACTIVE_CONNECTION_STATE_REASON_SERVICE_START_FAILED = 8 NM_ACTIVE_CONNECTION_STATE_REASON_NO_SECRETS = 9 NM_ACTIVE_CONNECTION_STATE_REASON_LOGIN_FAILED = 10 NM_ACTIVE_CONNECTION_STATE_REASON_CONNECTION_REMOVED = 11 NM_ACTIVE_CONNECTION_STATE_REASON_DEPENDENCY_FAILED = 12 NM_ACTIVE_CONNECTION_STATE_REASON_DEVICE_REALIZE_FAILED = 13 NM_ACTIVE_CONNECTION_STATE_REASON_DEVICE_REMOVED = 14 NM_SECRET_AGENT_GET_SECRETS_FLAG_NONE = 0 NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION = 1 NM_SECRET_AGENT_GET_SECRETS_FLAG_REQUEST_NEW = 2 NM_SECRET_AGENT_GET_SECRETS_FLAG_USER_REQUESTED = 4 NM_SECRET_AGENT_GET_SECRETS_FLAG_WPS_PBC_ACTIVE = 8 NM_SECRET_AGENT_GET_SECRETS_FLAG_ONLY_SYSTEM = 2147483648 NM_SECRET_AGENT_GET_SECRETS_FLAG_NO_ERRORS = 1073741824 NM_IP_TUNNEL_MODE_UNKNOWN = 0 NM_IP_TUNNEL_MODE_IPIP = 1 NM_IP_TUNNEL_MODE_GRE = 2 NM_IP_TUNNEL_MODE_SIT = 3 NM_IP_TUNNEL_MODE_ISATAP = 4 NM_IP_TUNNEL_MODE_VTI = 5 NM_IP_TUNNEL_MODE_IP6IP6 = 6 NM_IP_TUNNEL_MODE_IPIP6 = 7 NM_IP_TUNNEL_MODE_IP6GRE = 8 NM_IP_TUNNEL_MODE_VTI6 = 9 NM_IP_TUNNEL_MODE_GRETAP = 10 NM_IP_TUNNEL_MODE_IP6GRETAP = 11 NM_CHECKPOINT_CREATE_FLAG_NONE = 0 NM_CHECKPOINT_CREATE_FLAG_DESTROY_ALL = 1 NM_CHECKPOINT_CREATE_FLAG_DELETE_NEW_CONNECTIONS = 2 NM_CHECKPOINT_CREATE_FLAG_DISCONNECT_NEW_DEVICES = 4 NM_CHECKPOINT_CREATE_FLAG_ALLOW_OVERLAPPING = 8 NM_ROLLBACK_RESULT_OK = 0 NM_ROLLBACK_RESULT_ERR_NO_DEVICE = 1 NM_ROLLBACK_RESULT_ERR_DEVICE_UNMANAGED = 2 NM_ROLLBACK_RESULT_ERR_FAILED = 3 NM_SETTINGS_CONNECTION_FLAG_NONE = 0 NM_SETTINGS_CONNECTION_FLAG_UNSAVED = 1 NM_SETTINGS_CONNECTION_FLAG_NM_GENERATED = 2 NM_SETTINGS_CONNECTION_FLAG_VOLATILE = 4 NM_SETTINGS_CONNECTION_FLAG_EXTERNAL = 8 NM_ACTIVATION_STATE_FLAG_NONE = 0 NM_ACTIVATION_STATE_FLAG_IS_MASTER = 1 NM_ACTIVATION_STATE_FLAG_IS_SLAVE = 2 NM_ACTIVATION_STATE_FLAG_LAYER2_READY = 4 NM_ACTIVATION_STATE_FLAG_IP4_READY = 8 NM_ACTIVATION_STATE_FLAG_IP6_READY = 16 NM_ACTIVATION_STATE_FLAG_MASTER_HAS_SLAVES = 32 NM_ACTIVATION_STATE_FLAG_LIFETIME_BOUND_TO_PROFILE_VISIBILITY = 64 NM_ACTIVATION_STATE_FLAG_EXTERNAL = 128 NM_SETTINGS_ADD_CONNECTION2_FLAG_NONE = 0 NM_SETTINGS_ADD_CONNECTION2_FLAG_TO_DISK = 1 NM_SETTINGS_ADD_CONNECTION2_FLAG_IN_MEMORY = 2 NM_SETTINGS_ADD_CONNECTION2_FLAG_BLOCK_AUTOCONNECT = 32 NM_SETTINGS_UPDATE2_FLAG_NONE = 0 NM_SETTINGS_UPDATE2_FLAG_TO_DISK = 1 NM_SETTINGS_UPDATE2_FLAG_IN_MEMORY = 2 NM_SETTINGS_UPDATE2_FLAG_IN_MEMORY_DETACHED = 4 NM_SETTINGS_UPDATE2_FLAG_IN_MEMORY_ONLY = 8 NM_SETTINGS_UPDATE2_FLAG_VOLATILE = 16 NM_SETTINGS_UPDATE2_FLAG_BLOCK_AUTOCONNECT = 32 NM_SETTINGS_UPDATE2_FLAG_NO_REAPPLY = 64 NM_TERNARY_DEFAULT = -1 NM_TERNARY_FALSE = 0 NM_TERNARY_TRUE = 1 NM_MANAGER_RELOAD_FLAG_NONE = 0 NM_MANAGER_RELOAD_FLAG_CONF = 1 NM_MANAGER_RELOAD_FLAG_DNS_RC = 2 NM_MANAGER_RELOAD_FLAG_DNS_FULL = 4 NM_MANAGER_RELOAD_FLAG_ALL = 7 NM_DEVICE_INTERFACE_FLAG_NONE = 0 NM_DEVICE_INTERFACE_FLAG_UP = 1 NM_DEVICE_INTERFACE_FLAG_LOWER_UP = 2 NM_DEVICE_INTERFACE_FLAG_CARRIER = 65536 NM_CLIENT_PERMISSION_NONE = 0 NM_CLIENT_PERMISSION_ENABLE_DISABLE_NETWORK = 1 NM_CLIENT_PERMISSION_ENABLE_DISABLE_WIFI = 2 NM_CLIENT_PERMISSION_ENABLE_DISABLE_WWAN = 3 NM_CLIENT_PERMISSION_ENABLE_DISABLE_WIMAX = 4 NM_CLIENT_PERMISSION_SLEEP_WAKE = 5 NM_CLIENT_PERMISSION_NETWORK_CONTROL = 6 NM_CLIENT_PERMISSION_WIFI_SHARE_PROTECTED = 7 NM_CLIENT_PERMISSION_WIFI_SHARE_OPEN = 8 NM_CLIENT_PERMISSION_SETTINGS_MODIFY_SYSTEM = 9 NM_CLIENT_PERMISSION_SETTINGS_MODIFY_OWN = 10 NM_CLIENT_PERMISSION_SETTINGS_MODIFY_HOSTNAME = 11 NM_CLIENT_PERMISSION_SETTINGS_MODIFY_GLOBAL_DNS = 12 NM_CLIENT_PERMISSION_RELOAD = 13 NM_CLIENT_PERMISSION_CHECKPOINT_ROLLBACK = 14 NM_CLIENT_PERMISSION_ENABLE_DISABLE_STATISTICS = 15 NM_CLIENT_PERMISSION_ENABLE_DISABLE_CONNECTIVITY_CHECK = 16 NM_CLIENT_PERMISSION_WIFI_SCAN = 17 NM_CLIENT_PERMISSION_LAST = 17 NM_CLIENT_PERMISSION_RESULT_UNKNOWN = 0 NM_CLIENT_PERMISSION_RESULT_YES = 1 NM_CLIENT_PERMISSION_RESULT_AUTH = 2 NM_CLIENT_PERMISSION_RESULT_NO = 3 NM_VPN_SERVICE_STATE_UNKNOWN = 0 NM_VPN_SERVICE_STATE_INIT = 1 NM_VPN_SERVICE_STATE_SHUTDOWN = 2 NM_VPN_SERVICE_STATE_STARTING = 3 NM_VPN_SERVICE_STATE_STARTED = 4 NM_VPN_SERVICE_STATE_STOPPING = 5 NM_VPN_SERVICE_STATE_STOPPED = 6 NM_VPN_CONNECTION_STATE_UNKNOWN = 0 NM_VPN_CONNECTION_STATE_PREPARE = 1 NM_VPN_CONNECTION_STATE_NEED_AUTH = 2 NM_VPN_CONNECTION_STATE_CONNECT = 3 NM_VPN_CONNECTION_STATE_IP_CONFIG_GET = 4 NM_VPN_CONNECTION_STATE_ACTIVATED = 5 NM_VPN_CONNECTION_STATE_FAILED = 6 NM_VPN_CONNECTION_STATE_DISCONNECTED = 7 NM_VPN_CONNECTION_STATE_REASON_UNKNOWN = 0 NM_VPN_CONNECTION_STATE_REASON_NONE = 1 NM_VPN_CONNECTION_STATE_REASON_USER_DISCONNECTED = 2 NM_VPN_CONNECTION_STATE_REASON_DEVICE_DISCONNECTED = 3 NM_VPN_CONNECTION_STATE_REASON_SERVICE_STOPPED = 4 NM_VPN_CONNECTION_STATE_REASON_IP_CONFIG_INVALID = 5 NM_VPN_CONNECTION_STATE_REASON_CONNECT_TIMEOUT = 6 NM_VPN_CONNECTION_STATE_REASON_SERVICE_START_TIMEOUT = 7 NM_VPN_CONNECTION_STATE_REASON_SERVICE_START_FAILED = 8 NM_VPN_CONNECTION_STATE_REASON_NO_SECRETS = 9 NM_VPN_CONNECTION_STATE_REASON_LOGIN_FAILED = 10 NM_VPN_CONNECTION_STATE_REASON_CONNECTION_REMOVED = 11 NM_VPN_PLUGIN_FAILURE_LOGIN_FAILED = 0 NM_VPN_PLUGIN_FAILURE_CONNECT_FAILED = 1 NM_VPN_PLUGIN_FAILURE_BAD_IP_CONFIG = 2 NM_SECRET_AGENT_ERROR_NOT_AUTHORIZED = 0 NM_SECRET_AGENT_ERROR_INVALID_CONNECTION = 1 NM_SECRET_AGENT_ERROR_USER_CANCELED = 2 NM_SECRET_AGENT_ERROR_AGENT_CANCELED = 3 NM_SECRET_AGENT_ERROR_INTERNAL_ERROR = 4 NM_SECRET_AGENT_ERROR_NO_SECRETS = 5 ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1610805591.490605 python-networkmanager-2.2/PKG-INFO0000644000175100001640000000116400000000000016361 0ustar00runnerdockerMetadata-Version: 1.1 Name: python-networkmanager Version: 2.2 Summary: Easy communication with NetworkManager Home-page: http://github.com/seveas/python-networkmanager Author: Dennis Kaarsemaker Author-email: dennis@kaarsemaker.net License: UNKNOWN Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: zlib/libpng License Classifier: Operating System :: POSIX :: Linux Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: System :: Networking ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/README0000644000175100001640000000155100000000000016144 0ustar00runnerdockerpython-networkmanager Easy communication with NetworkManager ============================================================ python-networkmanager wraps NetworkManagers D-Bus interface so you can be less verbose when talking to NetworkManager from python. All interfaces have been wrapped in classes, properties are exposed as python properties and function calls are forwarded to the correct interface. See docs/index.rst for the documentation. An HTML version can be found on http://packages.python.org/python-networkmanager/ Requirements ============ Python 2.5 or newer (Python 3 is supported as well) and the python D-Bus bindings. Quick install instructions ========================== Stable version: $ pip install python-networkmanager Latest code: $ git clone http://github.com/seveas/python-networkmanager $ cd python-networkmanager $ python setup.py install ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1610805591.490605 python-networkmanager-2.2/docs/0000755000175100001640000000000000000000000016212 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/docs/Makefile0000644000175100001640000001105200000000000017651 0ustar00runnerdocker# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-networkmanager.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-networkmanager.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/python-networkmanager" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-networkmanager" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/docs/conf.py0000644000175100001640000001577200000000000017525 0ustar00runnerdocker# -*- coding: utf-8 -*- # # python-networkmanager documentation build configuration file, created by # sphinx-quickstart on Fri Nov 4 00:28:50 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os import sphinx_rtd_theme as theme # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'python-networkmanager' copyright = u'2011-2021, Dennis Kaarsemaker' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '2.2' # The full version, including alpha/beta/rc tags. release = '2.2' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [theme.get_html_theme_path()] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'python-networkmanagerdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'python-networkmanager.tex', u'python-networkmanager Documentation', u'Dennis Kaarsemaker', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'python-networkmanager', u'python-networkmanager Documentation', [u'Dennis Kaarsemaker'], 1) ] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/docs/index.rst0000644000175100001640000002356400000000000020065 0ustar00runnerdockerPython API to talk to NetworkManager ==================================== NetworkManager provides a detailed and capable D-Bus interface on the system bus. You can use this interface to query NetworkManager about the overall state of the network and details of network devices like current IP addresses or DHCP options, and to configure, activate and deactivate network connections. python-networkmanager takes this D-Bus interface and wraps D-Bus interfaces in classes and D-Bus methods and properties in their python equivalents. The :mod:`NetworkManager` module -------------------------------- .. module:: NetworkManager :platform: Linux systems with NetworkManager 0.9 and newer :synopsis: Talk to NetworkManager from python All the code is contained in one module: :mod:`NetworkManager`. Using it is as simple as you think it is: .. code-block:: py >>> import NetworkManager >>> NetworkManager.NetworkManager.Version '1.2.0' NetworkManager exposes a lot of information via D-Bus and also allows full control of network settings. The full D-Bus interface can be found on `NetworkManager project website`_. All interfaces listed there have been wrapped in classes as listed below. .. function:: const(prefix, value) Many of NetworkManagers D-Bus methods expect or return numeric constants, for which there are enums in the C source code. These constants, such as :data:`NM_STATE_CONNECTED_GLOBAL`, can all be found in the :mod:`NetworkManager` module as well. The :func:`const` function can help you translate them to text. For example: .. code-block:: py >>> NetworkManager.const('state', 40) 'connecting' >>> NetworkManager.const('device_type', 2) 'wifi' .. _`NetworkManager project website`: https://developer.gnome.org/NetworkManager/1.2/spec.html List of classes --------------- .. class:: ObjectVanished This Exception will be raised when you try to call a method or access a property on a dbus object that no longer exists. Objects can go missing if devices are removed, connections are disabled or NetworkManager is restarted. .. class:: NMDbusInterface This is the base class of all classes below. It handles the marshalling of data and the automatic creation of properties and methods. Each property, method and signal exposed via the D-Bus interface is automatically mirrored as an attribute of the actual classes. Moreover, the data is made slightly more usable by performing the following transformations on received and sent data. * IP addresses are returned as strings of the form :data:`1.2.3.4` instead of network byte ordered integers. * Route metrics are returned in host byte order, so you can use them as integers. * Mac addresses and BSSIDs are always returned as strings of the form :data:`00:11:22:33:44:55` instead of byte sequences. * Wireless SSID's are returned as strings instead of byte sequences. They will be decoded as UTF-8 data, so using any other encoding for your SSID will result in errors. * DHCP options are turned into integers or booleans as appropriate * Signals can be connected to using calls to On\ *SignalName* functions. Here's a short example to illustrate: >>> import NetworkManager >>> NetworkManager.NetworkManager.Version '1.4.4' >>> NetworkManager.NetworkManager.GetPermissions() {'org.freedesktop.NetworkManager.checkpoint-rollback': 'auth', 'org.freedesktop.NetworkManager.enable-disable-network': 'yes', ...} # Must have a mainloop to use signals >>> import dbus.mainloop.glib >>> dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) >>> NetworkManager.NetworkManager.OnStateChanged(handle_state_change) .. class:: TransientNMDbusInterface Subclasses of this class, which are ActiveConnection, NSP, IP[46]Config and DHCP[46]Config never survive a NetworkManager restart. Other objects may survive a restart, but get a different object path. .. class:: NetworkManager The main `NetworkManager `_ object; the `NetworkManager.Networkmanager` object is actually the singleton instance of this class. .. class:: Settings The `Settings `_ object, which can be used to add connections, list connections or update your hostname; the `NetworkManager.Settings` object is actually the singleton instance of this class. .. class:: AgentManager The `AgentManager `_ object, whose methods you'll need to call when implementing a secrets agent; the `NetworkManager.AgentManager` object is actually the singleton instance of this class. .. class:: Connection `Connection `_ objects represent network configurations configured by the user. .. class:: ActiveConnection .. class:: VPNConnection Active connections are represented by `ActiveConnection `_ objects. `VPNConnection `_ is a subclass for active VPN connection that implements both the Connection.Active and VPN.Connection interfaces. .. class:: IP4Config .. class:: IP6Config .. class:: DHCP4Config .. class:: DHCP6Config Active network connections and devices can all have `IPv4 `_, `IPv6 `_, `IPv4 DHCP `_ and `IPv6 DHCP `_ information attached to them, which is represented by instances of these classes. .. class:: AccessPoint Wifi `Accesspoints `_, as visibly by any 802.11 wifi interface. .. class:: NSP Wimax `Network Service Providers `_. .. class:: Device All device classes implement the `Device `_ interface, which gives you access to basic device properties. Note that you will never see instances of this class, only of its devicetype-specific subclasses which impletemnt not only the Device interface but also their own specific interface. Supported device types are `Adsl `_, `Bluetooth `_, `Bond `_, `Bridge `_, `Generic `_, `Infiniband `_, `IPTunnel `_, `Macvlan `_, `Modem `_, `OlpcMesh `_, `Team `_, `Tun `_, `Veth `_, `Vlan `_, `Vxlan `_, `Wimax `_, `Wired `_ and `Wireless `_ .. class:: SecretAgent The NetworkManager daemon can ask separate programs, called agents, for secrets if it needs them. The NetworkManager applet and the `nmcli` command-line tool are examples of such agents. You can also write such agents by subclassing the `SecretAgent` class and providing a `GetSecrets` method as in the following example, which returns a static password for each secret:: import dbus.mainloop.glib import GObject import NetworkManager class MyAgent(NetworkManager.SecretAgent): def GetSecrets(self, settings, connection, setting_name, hints, flags): return {setting_name: {'secrets': {'password': 'TopSecret!'}}} agent = MyAgent() dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) Gobject.MainLoop().run() Beware that NetworkManager will ask each agent in turn in what is in essence random order. Except it will prioritize the program that activated the connection. So if you want to make sure your agent is called first, activate the connection from the same application. .. toctree:: :maxdepth: 2 ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1610805591.490605 python-networkmanager-2.2/examples/0000755000175100001640000000000000000000000017100 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/examples/activate_connection.py0000644000175100001640000000227100000000000023473 0ustar00runnerdocker""" Activate a connection by name """ import NetworkManager import sys # Find the connection name = sys.argv[1] connections = NetworkManager.Settings.ListConnections() connections = dict([(x.GetSettings()['connection']['id'], x) for x in connections]) conn = connections[name] # Find a suitable device ctype = conn.GetSettings()['connection']['type'] if ctype == 'vpn': for dev in NetworkManager.NetworkManager.GetDevices(): if dev.State == NetworkManager.NM_DEVICE_STATE_ACTIVATED and dev.Managed: break else: print("No active, managed device found") sys.exit(1) else: dtype = { '802-11-wireless': NetworkManager.NM_DEVICE_TYPE_WIFI, '802-3-ethernet': NetworkManager.NM_DEVICE_TYPE_ETHERNET, 'gsm': NetworkManager.NM_DEVICE_TYPE_MODEM, }.get(ctype,ctype) devices = NetworkManager.NetworkManager.GetDevices() for dev in devices: if dev.DeviceType == dtype and dev.State == NetworkManager.NM_DEVICE_STATE_DISCONNECTED: break else: print("No suitable and available %s device found" % ctype) sys.exit(1) # And connect NetworkManager.NetworkManager.ActivateConnection(conn, dev, "/") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/examples/add_connection.py0000644000175100001640000000166700000000000022433 0ustar00runnerdocker""" Add a connection to NetworkManager. You do this by sending a dict to AddConnection. The dict below was generated with n-m dump on an existing connection and then anonymised """ import NetworkManager import uuid example_connection = { '802-11-wireless': {'mode': 'infrastructure', 'security': '802-11-wireless-security', 'ssid': 'n-m-example-connection'}, '802-11-wireless-security': {'auth-alg': 'open', 'key-mgmt': 'wpa-eap'}, '802-1x': {'eap': ['peap'], 'identity': 'eap-identity-goes-here', 'password': 'eap-password-goes-here', 'phase2-auth': 'mschapv2'}, 'connection': {'id': 'nm-example-connection', 'type': '802-11-wireless', 'uuid': str(uuid.uuid4())}, 'ipv4': {'method': 'auto'}, 'ipv6': {'method': 'auto'} } NetworkManager.Settings.AddConnection(example_connection) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/examples/connection_detail.py0000644000175100001640000000326600000000000023142 0ustar00runnerdocker""" Display detailed information about currently active connections. """ import NetworkManager c = NetworkManager.const for conn in NetworkManager.NetworkManager.ActiveConnections: settings = conn.Connection.GetSettings() for s in list(settings.keys()): if 'data' in settings[s]: settings[s + '-data'] = settings[s].pop('data') secrets = conn.Connection.GetSecrets() for key in secrets: settings[key].update(secrets[key]) devices = "" if conn.Devices: devices = " (on %s)" % ", ".join([x.Interface for x in conn.Devices]) print("Active connection: %s%s" % (settings['connection']['id'], devices)) size = max([max([len(y) for y in list(x.keys()) + ['']]) for x in settings.values()]) format = " %%-%ds %%s" % (size + 5) for key, val in sorted(settings.items()): print(" %s" % key) for name, value in val.items(): print(format % (name, value)) for dev in conn.Devices: print("Device: %s" % dev.Interface) print(" Type %s" % c('device_type', dev.DeviceType)) # print(" IPv4 address %s" % socket.inet_ntoa(struct.pack('L', dev.Ip4Address))) if hasattr(dev, 'HwAddress'): print(" MAC address %s" % dev.HwAddress) print(" IPv4 config") print(" Addresses") for addr in dev.Ip4Config.Addresses: print(" %s/%d -> %s" % tuple(addr)) print(" Routes") for route in dev.Ip4Config.Routes: print(" %s/%d -> %s (%d)" % tuple(route)) print(" Nameservers") for ns in dev.Ip4Config.Nameservers: print(" %s" % ns) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/examples/info.py0000644000175100001640000000412700000000000020411 0ustar00runnerdocker""" Display information about everything network-related that network-manager can say something about. """ import NetworkManager c = NetworkManager.const print("%-30s %s" % ("Version:", NetworkManager.NetworkManager.Version)) print("%-30s %s" % ("Hostname:", NetworkManager.Settings.Hostname)) print("%-30s %s" % ("Can modify:", NetworkManager.Settings.CanModify)) print("%-30s %s" % ("Networking enabled:", NetworkManager.NetworkManager.NetworkingEnabled)) print("%-30s %s" % ("Wireless enabled:", NetworkManager.NetworkManager.WirelessEnabled)) print("%-30s %s" % ("Wireless hw enabled:", NetworkManager.NetworkManager.WirelessHardwareEnabled)) print("%-30s %s" % ("Wwan enabled:", NetworkManager.NetworkManager.WwanEnabled)) print("%-30s %s" % ("Wwan hw enabled:", NetworkManager.NetworkManager.WwanHardwareEnabled)) print("%-30s %s" % ("Wimax enabled:", NetworkManager.NetworkManager.WimaxEnabled)) print("%-30s %s" % ("Wimax hw enabled:", NetworkManager.NetworkManager.WimaxHardwareEnabled)) print("%-30s %s" % ("Overall state:", c('state', NetworkManager.NetworkManager.State))) print("") print("Permissions") for perm, val in sorted(NetworkManager.NetworkManager.GetPermissions().items()): print("%-30s %s" % (perm[31:] + ':', val)) print("") print("Available network devices") print("%-10s %-19s %-20s %s" % ("Name", "State", "Driver", "Managed?")) for dev in NetworkManager.NetworkManager.GetDevices(): print("%-10s %-19s %-20s %s" % (dev.Interface, c('device_state', dev.State), dev.Driver, dev.Managed)) print("") print("Available connections") print("%-30s %s" % ("Name", "Type")) for conn in NetworkManager.Settings.ListConnections(): settings = conn.GetSettings()['connection'] print("%-30s %s" % (settings['id'], settings['type'])) print("") print("Active connections") print("%-30s %-20s %-10s %s" % ("Name", "Type", "Default", "Devices")) for conn in NetworkManager.NetworkManager.ActiveConnections: settings = conn.Connection.GetSettings()['connection'] print("%-30s %-20s %-10s %s" % (settings['id'], settings['type'], conn.Default, ", ".join([x.Interface for x in conn.Devices]))) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/examples/listener.py0000644000175100001640000000157700000000000021311 0ustar00runnerdocker""" Listen to some available signals from NetworkManager """ import dbus.mainloop.glib from gi.repository import GObject import NetworkManager import time def out(msg): print("%s %s" % (time.strftime('%H:%M:%S'), msg)) def statechange(nm, interface, signal, state): out("State changed to %s" % NetworkManager.const('STATE', state)) def adddevice(nm, interface, signal, device_path): try: out("Device %s added" % device_path.IpInterface) except NetworkManager.ObjectVanished: # Sometimes this signal is sent for *removed* devices. Ignore. pass def main(): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) NetworkManager.NetworkManager.OnStateChanged(statechange) NetworkManager.NetworkManager.OnDeviceAdded(adddevice) out("Waiting for signals") loop = GObject.MainLoop() loop.run() if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/examples/n-m0000755000175100001640000001777000000000000017531 0ustar00runnerdocker#!/usr/bin/python # # Command-line tool to interact with NetworkManager. With this tool, you can # inspect various configuration items and (de-)activate connections. # # (C) 2011-2021 Dennis Kaarsemaker # License: zlib from __future__ import print_function usage = """%prog [options] action [arguments] Actions: list - List all defined and active connections activate - Activate a connection deactivate - Deactivate a connection offline - Deactivate all connections enable - Enable specific connection types disable - Disable specific connection types info - Information about a connection""" import datetime from dbus.exceptions import DBusException import NetworkManager import optparse import socket import struct import sys PY3 = sys.version_info[0] >= 3 def main(): p = optparse.OptionParser(usage=usage) opts, args = p.parse_args() if not args: p.print_help() sys.exit(1) if args[0] == 'list': list_() elif args[0] == 'offline': offline() elif args[0] == 'visible': visible() elif len(args) < 2: p.print_help() sys.exit(1) elif args[0] == 'activate': activate(args[1:]) elif args[0] == 'deactivate': deactivate(args[1:]) elif args[0] == 'enable': enable(args[1:]) elif args[0] == 'disable': disable(args[1:]) elif args[0] == 'info': info(args[1:]) elif args[0] == 'dump': dump(args[1:]) else: p.print_help() sys.exit(1) def list_(): active = [x.Connection.GetSettings()['connection']['id'] for x in NetworkManager.NetworkManager.ActiveConnections] connections = [(x.GetSettings()['connection']['id'], x.GetSettings()['connection']['type']) for x in NetworkManager.Settings.ListConnections()] fmt = "%%s %%-%ds %%s" % max([len(x[0]) for x in connections]) for conn in sorted(connections): prefix = '* ' if conn[0] in active else ' ' print(fmt % (prefix, conn[0], conn[1])) def activate(names): connections = NetworkManager.Settings.ListConnections() connections = dict([(x.GetSettings()['connection']['id'], x) for x in connections]) if not NetworkManager.NetworkManager.NetworkingEnabled: NetworkManager.NetworkManager.Enable(True) for n in names: if n not in connections: print("No such connection: %s" % n, file=sys.stderr) sys.exit(1) print("Activating connection '%s'" % n) conn = connections[n] ctype = conn.GetSettings()['connection']['type'] if ctype == 'vpn': for dev in NetworkManager.NetworkManager.GetDevices(): if dev.State == NetworkManager.NM_DEVICE_STATE_ACTIVATED and dev.Managed: break else: print("No active, managed device found", file=sys.stderr) sys.exit(1) else: dtype = { '802-11-wireless': 'wlan', 'gsm': 'wwan', } if dtype in connection_types: enable(dtype) dtype = { '802-11-wireless': NetworkManager.NM_DEVICE_TYPE_WIFI, '802-3-ethernet': NetworkManager.NM_DEVICE_TYPE_ETHERNET, 'gsm': NetworkManager.NM_DEVICE_TYPE_MODEM, }.get(ctype,ctype) devices = NetworkManager.NetworkManager.GetDevices() for dev in devices: if dev.DeviceType == dtype and dev.State == NetworkManager.NM_DEVICE_STATE_DISCONNECTED: break else: print("No suitable and available %s device found" % ctype, file=sys.stderr) sys.exit(1) NetworkManager.NetworkManager.ActivateConnection(conn, dev, "/") def deactivate(names): active = NetworkManager.NetworkManager.ActiveConnections active = dict([(x.Connection.GetSettings()['connection']['id'], x) for x in active]) for n in names: if n not in active: print("No such connection: %s" % n, file=sys.stderr) sys.exit(1) print("Deactivating connection '%s'" % n) NetworkManager.NetworkManager.DeactivateConnection(active[n]) def offline(): try: NetworkManager.NetworkManager.Enable(False) except DBusException as e: if e.get_dbus_name() != 'org.freedesktop.NetworkManager.AlreadyEnabledOrDisabled': raise connection_types = ['wireless','wwan','wimax'] def enable(names): for n in names: if n not in connection_types: print("No such connection type: %s" % n, file=sys.stderr) sys.exit(1) setattr(NetworkManager.NetworkManager, n.title() + 'Enabled', True) def disable(names): for n in names: if n not in connection_types: print("No such connection type: %s" % n, file=sys.stderr) sys.exit(1) setattr(NetworkManager.NetworkManager, n.title() + 'Enabled', False) def info(names): connections = [x.GetSettings() for x in NetworkManager.Settings.ListConnections()] connections = dict([(x['connection']['id'], x) for x in connections]) for n in names: if not PY3: n = n.decode('utf-8') if n not in connections: print("No such connection: %s" % n, file=sys.stderr) return line = "Info about '%s'" % n print(line + "\n" + '=' * len(line)) conn = connections[n] print("Type:", conn['connection']['type']) print("Connect automatically:", ["No","Yes"][conn['connection'].get('autoconnect', True)]) if 'timestamp' in conn['connection']: print("Last connected on:", str(datetime.datetime.fromtimestamp(conn['connection']['timestamp']))) else: print("Never connected") print("IPv4 settings (%s)" % conn['ipv4']['method']) print(" Address(es):", ', '.join([x[0] for x in conn['ipv4']['addresses']]) or '(Automatic)') print(" DNS servers:", ', '.join(conn['ipv4']['dns']) or '(Automatic)') print(" Routes:", ", ".join(["%s/%d -> %s" % x[:3] for x in conn['ipv4']['routes']])) print(" Can be default route:", ["Yes","No"][conn['ipv4'].get('never-default', False)]) if conn['connection']['type'] == '802-3-ethernet': print("Physical link") print(" MAC address:", conn['802-3-ethernet'].get('mac-address', '(Automatic)')) elif conn['connection']['type'] == '802-11-wireless': print("Wireless link") print(" MAC address:", conn['802-11-wireless'].get('mac-address', '(Automatic)')) print(" SSID:", conn['802-11-wireless']['ssid']) if 'security' in conn['802-11-wireless']: print(" Wireless security:", conn[conn['802-11-wireless']['security']]['key-mgmt']) elif conn['connection']['type'] == 'vpn': print("VPN") print(" Type:", conn['vpn']['service-type'].rsplit('.',1)[-1]) print(" Remote:", conn['vpn']['data']['remote']) def dump(names): from pprint import pprint connections = {} for conn in NetworkManager.Settings.ListConnections(): settings = conn.GetSettings() secrets = conn.GetSecrets() for key in secrets: settings[key].update(secrets[key]) connections[settings['connection']['id']] = settings for n in names: if n not in connections: print("No such connection: %s" % n, file=sys.stderr) pprint(connections[n]) def visible(): for device in NetworkManager.NetworkManager.GetDevices(): if device.DeviceType != NetworkManager.NM_DEVICE_TYPE_WIFI: continue print("Visible on %s" % device.Udi[device.Udi.rfind('/')+1:]) device = device.SpecificDevice() active = device.ActiveAccessPoint aps = device.GetAccessPoints() for ap in aps: prefix = '* ' if ap.object_path == active.object_path else ' ' print("%s %s" % (prefix, ap.Ssid)) if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/examples/openvpn_over_ssh.py0000644000175100001640000000355400000000000023056 0ustar00runnerdocker""" I use a VPN that sits behind an SSH host, so I have to tunnel the VPN traffic over an SSH tunnel. I wanted to do that in one commadn, this prompted me to learn about the NetworkManager D-Bus API and now resulted in python-networkmanager. """ import dbus.mainloop.glib; dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) import NetworkManager import socket import subprocess import sys VPN_NAME = 'MyVpn' SSH_HOST = 'my.ssh.bastion.host.com' VPN_HOST = 'my.internal.vpn.host.com:1194' LOCALPORT = 1195 SSH = '/usr/bin/ssh' # Try connecting to LOCALPORT to see if the tunnel is alive sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(3) try: sock.connect(('localhost', LOCALPORT)) except socket.error: # Set up the SSH tunnel if it isn't print("Connecting to " + SSH_HOST) if subprocess.call([SSH, '-L%s:%s' % (LOCALPORT, VPN_HOST), '-f', '-n', '-N', SSH_HOST]) != 0: print("SSH to %s failed" % SSH_HOST) sys.exit(1) for conn in NetworkManager.Settings.ListConnections(): settings = conn.GetSettings() if settings['connection']['type'] == 'vpn' and settings['connection']['id'] == VPN_NAME: vpn = conn uuid = settings['connection']['uuid'] break else: print("VPN with name %s not found" % VPN_NAME) sys.exit(1) # Bail out of another vpn is active for conn in NetworkManager.NetworkManager.ActiveConnections: if conn.Vpn: vid = conn.Connection.GetSettings()['connection']['id'] print("The vpn %s is already active" % vid) sys.exit(1) # Activate VPN for dev in NetworkManager.NetworkManager.GetDevices(): if dev.State == NetworkManager.NM_DEVICE_STATE_ACTIVATED and dev.Managed: break else: print("No active, managed device found") sys.exit(1) print("Activating VPN") NetworkManager.NetworkManager.ActivateConnection(vpn, dev, "/") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/examples/otp-agent0000755000175100001640000000504600000000000020731 0ustar00runnerdocker#!/usr/bin/python3 # # Automate vpn connections that require a one-time password. # Requirements: # - secretstorage (find on pypi) # - pyotp (likewise) # # usage: ./otp-agent name-of-connection # # The connection will be activated and when networkmanager asks for a secret, # it will be provided. If the secret isn't known yet, it will be asked and # stored with the secretstorage api (so in e.g. your gnome keyring) import dbus.mainloop.glib from gi.repository import GObject import NetworkManager import pyotp import traceback import secretstorage import sys def main(): print("Connecting to %s" % sys.argv[1]) dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) loop = GObject.MainLoop() agent = SecretAgent(loop) for connection in NetworkManager.Settings.ListConnections(): settings = connection.GetSettings()['connection'] if settings['id'] == sys.argv[1]: NetworkManager.NetworkManager.ActivateConnection(connection, "/", "/") loop.run() break else: print("Connection %s not found" % sys.argv[1]) class SecretAgent(NetworkManager.SecretAgent): def __init__(self, loop): self.loop = loop self.collection = secretstorage.get_default_collection(secretstorage.dbus_init()) super(SecretAgent, self).__init__('net.seveas.otp-agent') def GetSecrets(self, settings, connection, setting_name, hints, flags): try: print("NetworkManager is asking us for a secret") if setting_name != 'vpn': return {} attrs = { 'xdg:schema': 'net.seveas.otp-agent', 'hostname': settings['vpn']['data']['remote'], } items = list(self.collection.search_items(attrs)) if not items: print("No secrets found yet, asking user") secret = input("Enter secret code for %s: " % settings['vpn']['data']['remote']) self.collection.create_item(settings['vpn']['data']['remote'], attrs, secret) items = list(self.collection.search_items(attrs)) else: print("Found secret key, generating otp code") secret = items[0].get_secret().decode('ascii') otp = pyotp.TOTP(secret).now() print("otp code: %s" % otp) return {setting_name: {'secrets': {'password': otp}}} except: import traceback traceback.print_exc() return {} finally: self.loop.quit() if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/examples/ssids.py0000644000175100001640000000045500000000000020603 0ustar00runnerdocker""" Display all visible SSIDs """ import NetworkManager for dev in NetworkManager.NetworkManager.GetDevices(): if dev.DeviceType != NetworkManager.NM_DEVICE_TYPE_WIFI: continue for ap in dev.GetAccessPoints(): print('%-30s %dMHz %d%%' % (ap.Ssid, ap.Frequency, ap.Strength)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/examples/wifi_monitor.py0000644000175100001640000000276700000000000022173 0ustar00runnerdocker""" Show and monitor available access points """ from gi.repository import GObject import dbus.mainloop.glib import NetworkManager # Cache the ssids, as the SSid property will be unavailable when an AP # disappears ssids = {} def main(): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) # Listen for added and removed access points for dev in NetworkManager.Device.all(): if dev.DeviceType == NetworkManager.NM_DEVICE_TYPE_WIFI: dev.OnAccessPointAdded(ap_added) dev.OnAccessPointRemoved(ap_removed) for ap in NetworkManager.AccessPoint.all(): try: ssids[ap.object_path] = ap.Ssid print("* %-30s %s %sMHz %s%%" % (ap.Ssid, ap.HwAddress, ap.Frequency, ap.Strength)) ap.OnPropertiesChanged(ap_propchange) except NetworkManager.ObjectVanished: pass GObject.MainLoop().run() def ap_added(dev, interface, signal, access_point): ssids[access_point.object_path] = access_point.Ssid print("+ %-30s %s %sMHz %s%%" % (access_point.Ssid, access_point.HwAddress, access_point.Frequency, access_point.Strength)) access_point.OnPropertiesChanged(ap_propchange) def ap_removed(dev, interface, signal, access_point): print("- %-30s" % ssids.pop(access_point.object_path)) def ap_propchange(ap, interface, signal, properties): if 'Strength' in properties: print(" %-30s %s %sMHz %s%%" % (ap.Ssid, ap.HwAddress, ap.Frequency, properties['Strength'])) if __name__ == '__main__': main() ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1610805591.490605 python-networkmanager-2.2/python_networkmanager.egg-info/0000755000175100001640000000000000000000000023401 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805591.0 python-networkmanager-2.2/python_networkmanager.egg-info/PKG-INFO0000644000175100001640000000116400000000000024500 0ustar00runnerdockerMetadata-Version: 1.1 Name: python-networkmanager Version: 2.2 Summary: Easy communication with NetworkManager Home-page: http://github.com/seveas/python-networkmanager Author: Dennis Kaarsemaker Author-email: dennis@kaarsemaker.net License: UNKNOWN Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: zlib/libpng License Classifier: Operating System :: POSIX :: Linux Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: System :: Networking ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805591.0 python-networkmanager-2.2/python_networkmanager.egg-info/SOURCES.txt0000644000175100001640000000141600000000000025267 0ustar00runnerdockerCOPYING MANIFEST.in NetworkManager.py README setup.py docs/Makefile docs/conf.py docs/index.rst examples/activate_connection.py examples/add_connection.py examples/connection_detail.py examples/info.py examples/listener.py examples/n-m examples/openvpn_over_ssh.py examples/otp-agent examples/ssids.py examples/wifi_monitor.py python_networkmanager.egg-info/PKG-INFO python_networkmanager.egg-info/SOURCES.txt python_networkmanager.egg-info/dependency_links.txt python_networkmanager.egg-info/requires.txt python_networkmanager.egg-info/top_level.txt test/test_accesspoint.py test/test_activeconnection.py test/test_agentmanager.py test/test_connection.py test/test_connection_addremove.py test/test_devices.py test/test_ipconfig.py test/test_networkmanager.py test/test_settings.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805591.0 python-networkmanager-2.2/python_networkmanager.egg-info/dependency_links.txt0000644000175100001640000000000100000000000027447 0ustar00runnerdocker ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805591.0 python-networkmanager-2.2/python_networkmanager.egg-info/requires.txt0000644000175100001640000000002000000000000025771 0ustar00runnerdockerdbus-python six ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805591.0 python-networkmanager-2.2/python_networkmanager.egg-info/top_level.txt0000644000175100001640000000001700000000000026131 0ustar00runnerdockerNetworkManager ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1610805591.490605 python-networkmanager-2.2/setup.cfg0000644000175100001640000000004600000000000017103 0ustar00runnerdocker[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/setup.py0000755000175100001640000000140200000000000016774 0ustar00runnerdocker#!/usr/bin/python from setuptools import setup setup(name = "python-networkmanager", version = "2.2", author = "Dennis Kaarsemaker", author_email = "dennis@kaarsemaker.net", url = "http://github.com/seveas/python-networkmanager", description = "Easy communication with NetworkManager", py_modules = ["NetworkManager"], install_requires = ["dbus-python", "six"], classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: zlib/libpng License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: System :: Networking', ] ) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1610805591.490605 python-networkmanager-2.2/test/0000755000175100001640000000000000000000000016241 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/test/test_accesspoint.py0000644000175100001640000000243500000000000022171 0ustar00runnerdockerfrom test import * class AccessPointTest(TestCase): def test_accesspoints(self): for dev in NetworkManager.NetworkManager.Devices: if isinstance(dev, NetworkManager.Wireless): for ap in dev.AccessPoints: self.assertIsInstance(ap.Flags, int) # Frequencies from https://en.wikipedia.org/wiki/List_of_WLAN_channels f = ap.Frequency if not ( (f > 2400 and f < 2500) or (f > 3650 and f < 3700) or (f > 4900 and f < 6000)): self.fail("Frequency is not a valid wifi frequency") self.assertIsMacAddress(ap.HwAddress) self.assertIsInstance(ap.LastSeen, int) self.assertIsInstance(ap.MaxBitrate, int) self.assertIsInstance(ap.WpaFlags, int) self.assertIsInstance(ap.RsnFlags, int) self.assertLess(ap.Strength, 100) self.assertIsInstance(ap.Ssid, six.text_type) self.assertIn(ap.Mode, (NetworkManager.NM_802_11_MODE_ADHOC, NetworkManager.NM_802_11_MODE_INFRA, NetworkManager.NM_802_11_MODE_AP)) if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/test/test_activeconnection.py0000644000175100001640000000266700000000000023220 0ustar00runnerdockerfrom test import * class ActiveConnectionTest(TestCase): def test_properties(self): for conn in NetworkManager.NetworkManager.ActiveConnections: self.assertIsInstance(conn.Connection, NetworkManager.Connection) for device in conn.Devices: self.assertIsInstance(device, NetworkManager.Device) if conn.Connection.GetSettings()['connection']['type'] == '802-11-wireless': self.assertIsInstance(conn.SpecificObject, NetworkManager.AccessPoint) if conn.Vpn: self.assertIsInstance(conn, NetworkManager.VPNConnection) self.assertIsInstance(conn.Banner, six.text_type) self.assertIsInstance(conn.SpecificObject, NetworkManager.ActiveConnection) self.assertTrue(conn.State == NetworkManager.NM_ACTIVE_CONNECTION_STATE_ACTIVATED) self.assertIsInstance(conn.Ip4Config, NetworkManager.IP4Config) self.assertIsInstance(conn.Ip6Config, (NetworkManager.IP6Config, type(None))) self.assertIsInstance(conn.Dhcp4Config, (NetworkManager.DHCP4Config, type(None))) self.assertIsInstance(conn.Dhcp6Config, (NetworkManager.DHCP6Config, type(None))) if conn.Master != None: self.assertIsInstance(conn.Master, NetworkManager.Device) self.assertEqual(conn.Master, conn.SpecificObject.Devices[0]) if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/test/test_agentmanager.py0000644000175100001640000000040400000000000022301 0ustar00runnerdockerfrom test import * class AgentManagerTest(TestCase): def test_registration(self): NetworkManager.AgentManager.Register('python-network-manager-test') NetworkManager.AgentManager.Unregister() if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/test/test_connection.py0000644000175100001640000000460600000000000022017 0ustar00runnerdockerfrom test import * class ConnectionTest(TestCase): def test_settings(self): for connection in NetworkManager.Settings.ListConnections(): settings = connection.GetSettings() self.assertIn(settings['connection']['type'], settings) secrets = connection.GetSecrets() for key in settings: self.assertIn(key, secrets) if 'ipv4' in settings: for address, prefix, gateway in settings['ipv4']['addresses']: self.assertIsIpAddress(address) self.assertIsIpAddress(gateway) if 'ipv6' in settings: for address, prefix, gateway in settings['ipv6']['addresses']: self.assertIsIpAddress(address) self.assertIsIpAddress(gateway) def test_update(self): active = [x.Connection for x in NetworkManager.NetworkManager.ActiveConnections] for connection in NetworkManager.Settings.Connections: if connection in active: continue settings = connection.GetSettings() connection.Update(settings) # FIXME: this causes assertion failures in n-m, which cause the dbus call to hang #settings['connection']['timestamp'] -= 1 #connection.UpdateUnsaved(settings) #self.assertTrue(connection.Unsaved) #print("Saving") #connection.Save() #print("Saved") #self.assertFalse(connection.Unsaved) break def test_secrets(self): active = [x.Connection for x in NetworkManager.NetworkManager.ActiveConnections] key = '802-11-wireless-security' for connection in NetworkManager.Settings.Connections: if connection in active: continue settings = connection.GetSettings() if key not in settings: continue secrets = connection.GetSecrets() if not secrets[key]: continue settings[key].update(secrets[key]) connection.ClearSecrets() secrets = connection.GetSecrets() self.assertEqual(secrets[key], {}) connection.Update(settings) secrets = connection.GetSecrets() self.assertNotEqual(secrets[key], {}) break if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/test/test_connection_addremove.py0000644000175100001640000000376300000000000024050 0ustar00runnerdockerfrom test import * class ConnectionAddRemoveTest(TestCase): def test_activate(self): active = NetworkManager.NetworkManager.ActiveConnections[0] ap = active.SpecificObject conn = active.Connection dev = active.Devices[0] NetworkManager.NetworkManager.DeactivateConnection(active) self.waitForDisconnection() NetworkManager.NetworkManager.ActivateConnection(conn, dev, ap) self.waitForConnection() def test_delete_addactivate(self): active = NetworkManager.NetworkManager.ActiveConnections[0] ap = active.SpecificObject conn = active.Connection dev = active.Devices[0] settings = conn.GetSettings() typ = settings['connection']['type'] if 'security' in settings[typ]: key2 = settings[typ]['security'] settings[key2].update(conn.GetSecrets(key2)[key2]) conn.Delete() self.waitForDisconnection() conn, active = NetworkManager.NetworkManager.AddAndActivateConnection(settings, dev, ap) self.assertIsInstance(conn, NetworkManager.Connection) self.assertIsInstance(active, NetworkManager.ActiveConnection) self.waitForConnection() def test_delete_add_activate(self): active = NetworkManager.NetworkManager.ActiveConnections[0] ap = active.SpecificObject conn = active.Connection dev = active.Devices[0] settings = conn.GetSettings() typ = settings['connection']['type'] if 'security' in settings[typ]: key2 = settings[typ]['security'] settings[key2].update(conn.GetSecrets(key2)[key2]) conn.Delete() self.waitForDisconnection() conn = NetworkManager.Settings.AddConnection(settings) self.assertIsInstance(conn, NetworkManager.Connection) NetworkManager.NetworkManager.ActivateConnection(conn, dev, ap) self.waitForConnection() if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/test/test_devices.py0000644000175100001640000000347400000000000021304 0ustar00runnerdockerfrom test import * class DeviceTest(TestCase): def test_devices(self): for device in NetworkManager.NetworkManager.Devices: self.assertIsStrictSubclass(type(device), NetworkManager.Device) if device.Dhcp4Config: self.assertIsInstance(device.Dhcp4Config, NetworkManager.DHCP4Config) if device.Dhcp6Config: self.assertIsInstance(device.Dhcp6Config, NetworkManager.DHCP6Config) if device.Ip4Config: self.assertIsInstance(device.Ip4Config, NetworkManager.IP4Config) if device.Ip6Config: self.assertIsInstance(device.Ip6Config, NetworkManager.IP6Config) if device.Ip4Address: self.assertIsIpAddress(device.Ip4Address) if hasattr(device, 'HwAddress') and device.HwAddress: self.assertIsMacAddress(device.HwAddress) if hasattr(device, 'PermHwAddress') and device.PermHwAddress: self.assertIsMacAddress(device.PermHwAddress) if device.DeviceType == NetworkManager.NM_DEVICE_TYPE_WIFI: for ap in device.AccessPoints: self.assertIsInstance(ap, NetworkManager.AccessPoint) device.RequestScan({}) elif device.DeviceType == NetworkManager.NM_DEVICE_TYPE_ETHERNET: self.assertIn(device.Carrier, (True, False)) elif device.DeviceType == NetworkManager.NM_DEVICE_TYPE_GENERIC: self.assertIsInstance(device.TypeDescription, six.text_type) elif device.DeviceType == NetworkManager.NM_DEVICE_TYPE_TUN: if device.Owner != -1: import pwd pwd.getpwuid(device.Owner) else: self.fail("I don't know how to test %s devices" % type(device).__name__) if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/test/test_ipconfig.py0000644000175100001640000000462400000000000021456 0ustar00runnerdockerfrom test import * class IpConfigTest(TestCase): def test_configs(self): for device in NetworkManager.NetworkManager.Devices: if device.State != NetworkManager.NM_DEVICE_STATE_ACTIVATED: continue self.do_check(device) for connection in NetworkManager.NetworkManager.ActiveConnections: self.do_check(connection) def do_check(self, thing): if thing.Dhcp4Config: self.assertIsInstance(thing.Dhcp4Config, NetworkManager.DHCP4Config) self.assertIsInstance(thing.Dhcp4Config.Options, dict) o = thing.Dhcp4Config.Options self.assertIsInstance(o['domain_name_servers'], list) self.assertIsInstance(o['ntp_servers'], list) self.assertIsIpAddress(o['ip_address']) for key in o: if key.endswith('_requested'): self.assertTrue(o[key]) if thing.Dhcp6Config: self.assertIsInstance(thing.Dhcp6Config, NetworkManager.DHCP6Config) self.assertIsInstance(thing.Dhcp6Config.Options, dict) for c in (thing.Ip4Config, thing.Ip6Config): if not c: continue for addr, prefix, gateway in c.Addresses: self.assertIsIpAddress(addr) self.assertIsIpAddress(gateway) self.assertIsIpNetwork(addr, prefix) for data in c.AddressData: self.assertIsIpAddress(data['address']) self.assertIsIpNetwork(data['address'], data['prefix']) if 'peer' in data: self.assertIsIpAddress(data['peer']) if c.Gateway: self.assertIsIpAddress(c.Gateway) for addr in c.Nameservers: self.assertIsIpAddress(addr) for addr in getattr(c, 'WinsServers', []): self.assertIsIpAddress(addr) for dest, prefix, next_hop, metric in c.Routes: self.assertIsIpNetwork(dest, prefix) self.assertIsIpAddress(next_hop) self.assertLessEqual(metric, 1000) for data in c.RouteData: self.assertIsIpNetwork(data['dest'], data['prefix']) if 'next-hop' in data: self.assertIsIpAddress(data['next-hop']) self.assertLessEqual(data['metric'], 1000) if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/test/test_networkmanager.py0000644000175100001640000000642500000000000022705 0ustar00runnerdockerfrom test import * class NetworkManagerTest(TestCase): def test_properties(self): self.assertIsInstance(NetworkManager.NetworkManager.NetworkingEnabled, bool) self.assertIsInstance(NetworkManager.NetworkManager.Metered, int) self.assertIsInstance(NetworkManager.NetworkManager.Version, six.string_types) self.assertIsInstance(NetworkManager.NetworkManager.ActiveConnections, list) for conn in NetworkManager.NetworkManager.ActiveConnections: self.assertIsInstance(conn, NetworkManager.ActiveConnection) self.assertIsInstance(NetworkManager.NetworkManager.Devices, list) for dev in NetworkManager.NetworkManager.Devices: self.assertIsInstance(dev, NetworkManager.Device) self.assertIsInstance(NetworkManager.NetworkManager.PrimaryConnection, NetworkManager.ActiveConnection) @unittest.skipUnless(have_permission('sleep-wake'), "Not allowed to make networkmanager sleep") def test_sleep(self): NetworkManager.NetworkManager.Sleep(True) self.assertRaisesDBus('AlreadyAsleepOrAwake', NetworkManager.NetworkManager.Sleep, True) NetworkManager.NetworkManager.Sleep(False) self.assertRaisesDBus('AlreadyAsleepOrAwake', NetworkManager.NetworkManager.Sleep, False) self.waitForConnection() def test_enable(self): NetworkManager.NetworkManager.Enable(False) self.assertRaisesDBus('AlreadyEnabledOrDisabled', NetworkManager.NetworkManager.Enable, False) NetworkManager.NetworkManager.Enable(True) self.assertRaisesDBus('AlreadyEnabledOrDisabled', NetworkManager.NetworkManager.Enable, True) self.waitForConnection() @unittest.skipUnless(os.getuid() == 0, "Must be root to modify logging") def test_logging(self): level1, domains = NetworkManager.NetworkManager.GetLogging() self.assertIn(level1, ['ERR', 'WARN', 'INFO', 'DEBUG', 'TRACE']) self.assertIn('PLATFORM', domains) NetworkManager.NetworkManager.SetLogging("KEEP", "PLATFORM:DEBUG") level2, domains = NetworkManager.NetworkManager.GetLogging() self.assertEqual(level1, level2) self.assertIn('PLATFORM:DEBUG', domains) self.assertIn('CORE', domains) NetworkManager.NetworkManager.SetLogging("KEEP", "PLATFORM:" + level1) level2, domains = NetworkManager.NetworkManager.GetLogging() self.assertIn('PLATFORM', domains) self.assertNotIn('PLATFORM:DEBUG', domains) def test_permissions(self): permissions = NetworkManager.NetworkManager.GetPermissions() self.assertIsInstance(permissions, dict) for key in permissions: self.assertTrue(key.startswith('org.freedesktop.NetworkManager.')) self.assertIn(permissions[key], ('yes', 'no', 'auth')) def test_devices(self): dev1 = NetworkManager.NetworkManager.GetDevices() dev2 = NetworkManager.NetworkManager.GetAllDevices() for dev in dev1: self.assertIsInstance(dev, NetworkManager.Device) self.assertIsStrictSubclass(dev.__class__, NetworkManager.Device) self.assertIn(dev, dev2) dev = NetworkManager.NetworkManager.GetDeviceByIpIface(dev1[0].IpInterface) self.assertEqual(dev, dev1[0]) if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1610805582.0 python-networkmanager-2.2/test/test_settings.py0000644000175100001640000000226100000000000021513 0ustar00runnerdockerfrom test import * import socket class SettingsTest(TestCase): def test_connections(self): conn1 = NetworkManager.Settings.Connections conn2 = NetworkManager.Settings.ListConnections() self.assertIsInstance(conn1, list) for conn in conn1: self.assertIn(conn, conn2) for conn in conn2: self.assertIn(conn, conn1) conn = NetworkManager.Settings.GetConnectionByUuid(conn1[0].GetSettings()['connection']['uuid']) @unittest.skipUnless(os.getuid() == 0, "Must be root to reload connections") def test_reload(self): self.assertTrue(NetworkManager.Settings.ReloadConnections()) @unittest.skipUnless(have_permission('settings.modify.hostname'), "don't have permission to modify the hostname") def test_hostname(self): hn = NetworkManager.Settings.Hostname self.assertEqual(hn, socket.gethostname()) NetworkManager.Settings.SaveHostname(hn + '-test') self.assertEqual(NetworkManager.Settings.Hostname, hn + '-test') NetworkManager.Settings.SaveHostname(hn) self.assertEqual(NetworkManager.Settings.Hostname, hn) if __name__ == '__main__': unittest.main()