def __init__(self, seed): service_path = PathConfiguration.test_networkmanager_service_path() self._conn = dbus.SessionBus() env = os.environ.copy() env['NM_TEST_NETWORKMANAGER_SERVICE_SEED'] = seed p = subprocess.Popen([sys.executable, service_path], stdin=subprocess.PIPE, env=env) start = NM.utils_get_timestamp_msec() while True: if p.poll() is not None: p.stdin.close() if p.returncode == 77: raise unittest.SkipTest( 'the stub service %s exited with status 77' % (service_path)) raise Exception('the stub service %s exited unexpectedly' % (service_path)) nmobj = self._conn_get_main_object(self._conn) if nmobj is not None: break if (NM.utils_get_timestamp_msec() - start) >= 2000: p.stdin.close() p.kill() Util.popen_wait(p, 1000) raise Exception( "after starting stub service the D-Bus name was not claimed in time" ) self._nmobj = nmobj self._nmiface = dbus.Interface( nmobj, "org.freedesktop.NetworkManager.LibnmGlibTest") self._p = p
def create_connection(self): if not self.Config['apn']: self._raise_or_error_handler( NMConnectionError( 'No apn configured, make sure to configure dialup settings' )) return conn = NM.SimpleConnection() conn_id = 'blueman dun for %s' % self.device['Alias'] conn_uuid = str(uuid.uuid4()) conn_sett = NM.SettingConnection(type='bluetooth', id=conn_id, uuid=conn_uuid, autoconnect=False) conn_sett_bt = NM.SettingBluetooth(type=self.conntype, bdaddr=self.bdaddr) conn_sett_gsm = NM.SettingGsm(apn=self.Config['apn'], number=self.Config['number']) conn.add_setting(conn_sett) conn.add_setting(conn_sett_bt) conn.add_setting(conn_sett_gsm) self.client.add_connection_async(conn, True, None, self._on_connection_added, conn_uuid)
def _on_device_state_changed(self, device, new_state, old_state, reason): new = NM.DeviceState(new_state) old = NM.DeviceState(old_state) state_reason = NM.DeviceStateReason(reason) logging.debug( 'New: %s Old: %s Reason: %s' % (new.value_nick, old.value_nick, state_reason.value_nick)) error_msg = None reply_msg = None if new == NM.DeviceState.FAILED: error_msg = 'Connection failed with reason: %s' % state_reason.value_nick elif new == NM.DeviceState.ACTIVATED: reply_msg = 'Connection sucesfully activated' elif (new <= NM.DeviceState.DISCONNECTED or new == NM.DeviceState.DEACTIVATING) and \ (NM.DeviceState.DISCONNECTED < old <= NM.DeviceState.ACTIVATED): error_msg = 'Connection disconnected with reason %s' % state_reason.value_nick else: return # Keep checking the state changes # We are done with state changes device.disconnect(self._statehandler) if error_msg is None: self._return_or_reply_handler(reply_msg) else: logging.debug(error_msg) self._raise_or_error_handler(NMConnectionError(error_msg))
def clone_connection(context, name, uuid, flags="TO_DISK"): import gi gi.require_version('NM', '1.0') from gi.repository import GLib, NM main_loop = GLib.MainLoop() nm_client = NM.Client.new(None) if uuid == "random": uuid = NM.utils_uuid_generate() elif uuid == "noted": uuid = context.noted['noted-value'] elif uuid.startswith("noted."): index = uuid.replace("noted.","") uuid = context.noted[index] nm_flags = parse_NM_settings_flags_string(NM.SettingsAddConnection2Flags, flags) con2 = NM.SimpleConnection() s_con = NM.SettingConnection(type="802-3-ethernet", id=name, uuid=uuid) con2.add_setting(s_con) result = {} def _add_connection2_cb(cl, async_result, user_data): try: nm_client.add_connection2_finish(async_result) except Exception as e: result['error'] = e main_loop.quit() nm_client.add_connection2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL), nm_flags, None, False, None, _add_connection2_cb, None) main_loop.run() if 'error' in result: raise Exception('add connection %s failed: %s' % (name, result['error']))
def _print(msg=""): if is_libnm_debug(): # we want to use the same logging mechanism as libnm's debug # logging with "LIBNM_CLIENT_DEBUG=trace,stdout". NM.utils_print(0, msg + "\n") return print(msg)
def _on_device_state_changed(self, device: NM.Device, new_state: int, old_state: int, reason: int) -> None: new = NM.DeviceState(new_state) old = NM.DeviceState(old_state) state_reason = NM.DeviceStateReason(reason) logging.debug( f"New: {new.value_nick} Old: {old.value_nick} Reason: {state_reason.value_nick}" ) error_msg = None if new == NM.DeviceState.FAILED: error_msg = f"Connection failed with reason: {state_reason.value_nick}" elif new == NM.DeviceState.ACTIVATED: logging.debug("Connection successfully activated") elif (new <= NM.DeviceState.DISCONNECTED or new == NM.DeviceState.DEACTIVATING) and \ (NM.DeviceState.DISCONNECTED < old <= NM.DeviceState.ACTIVATED): error_msg = f"Connection disconnected with reason {state_reason.value_nick}" else: return # Keep checking the state changes # We are done with state changes assert self._statehandler is not None GObject.signal_handler_disconnect(device, self._statehandler) if error_msg is None: self.reply_handler() else: logging.debug(error_msg) self.error_handler(NMConnectionError(error_msg))
def update_connection(self, connection): """Update NM RemoteConnection from the object. :param connection: connection to be updated from the object :type connection: NM.RemoteConnection """ # ipv4 settings if self.ip == "dhcp": method4 = NM.SETTING_IP4_CONFIG_METHOD_AUTO elif self.ip: method4 = NM.SETTING_IP4_CONFIG_METHOD_MANUAL else: method4 = NM.SETTING_IP4_CONFIG_METHOD_DISABLED connection.remove_setting(NM.SettingIP4Config) s_ip4 = NM.SettingIP4Config.new() s_ip4.set_property(NM.SETTING_IP_CONFIG_METHOD, method4) if method4 == NM.SETTING_IP4_CONFIG_METHOD_MANUAL: prefix4 = network.netmask2prefix(self.netmask) addr4 = NM.IPAddress.new(socket.AF_INET, self.ip, prefix4) s_ip4.add_address(addr4) if self.gateway: s_ip4.props.gateway = self.gateway connection.add_setting(s_ip4) # ipv6 settings if self.ipv6 == "ignore": method6 = NM.SETTING_IP6_CONFIG_METHOD_IGNORE elif not self.ipv6 or self.ipv6 == "auto": method6 = NM.SETTING_IP6_CONFIG_METHOD_AUTO elif self.ipv6 == "dhcp": method6 = NM.SETTING_IP6_CONFIG_METHOD_DHCP else: method6 = NM.SETTING_IP6_CONFIG_METHOD_MANUAL connection.remove_setting(NM.SettingIP6Config) s_ip6 = NM.SettingIP6Config.new() s_ip6.set_property(NM.SETTING_IP_CONFIG_METHOD, method6) if method6 == NM.SETTING_IP6_CONFIG_METHOD_MANUAL: addr6, _slash, prefix6 = self.ipv6.partition("/") if prefix6: prefix6 = int(prefix6) else: prefix6 = 64 addr6 = NM.IPAddress.new(socket.AF_INET6, addr6, prefix6) s_ip6.add_address(addr6) if self.ipv6gateway: s_ip6.props.gateway = self.ipv6gateway connection.add_setting(s_ip6) # nameservers if self.nameserver: for ns in [str.strip(i) for i in self.nameserver.split(",")]: if NM.utils_ipaddr_valid(socket.AF_INET6, ns): s_ip6.add_dns(ns) elif NM.utils_ipaddr_valid(socket.AF_INET, ns): s_ip4.add_dns(ns) else: log.error("IP address %s is not valid", ns)
def update_connection(self, connection): """Update NM RemoteConnection from the object. :param connection: connection to be updated from the object :type connection: NM.RemoteConnection """ # ipv4 settings if self.ip == "dhcp": method4 = NM.SETTING_IP4_CONFIG_METHOD_AUTO elif self.ip: method4 = NM.SETTING_IP4_CONFIG_METHOD_MANUAL else: method4 = NM.SETTING_IP4_CONFIG_METHOD_DISABLED connection.remove_setting(NM.SettingIP4Config) s_ip4 = NM.SettingIP4Config.new() s_ip4.set_property(NM.SETTING_IP_CONFIG_METHOD, method4) if method4 == NM.SETTING_IP4_CONFIG_METHOD_MANUAL: prefix4 = network.netmask_to_prefix(self.netmask) addr4 = NM.IPAddress.new(socket.AF_INET, self.ip, prefix4) s_ip4.add_address(addr4) if self.gateway: s_ip4.props.gateway = self.gateway connection.add_setting(s_ip4) # ipv6 settings if self.ipv6 == "ignore": method6 = NM.SETTING_IP6_CONFIG_METHOD_IGNORE elif not self.ipv6 or self.ipv6 == "auto": method6 = NM.SETTING_IP6_CONFIG_METHOD_AUTO elif self.ipv6 == "dhcp": method6 = NM.SETTING_IP6_CONFIG_METHOD_DHCP else: method6 = NM.SETTING_IP6_CONFIG_METHOD_MANUAL connection.remove_setting(NM.SettingIP6Config) s_ip6 = NM.SettingIP6Config.new() s_ip6.set_property(NM.SETTING_IP_CONFIG_METHOD, method6) if method6 == NM.SETTING_IP6_CONFIG_METHOD_MANUAL: addr6, _slash, prefix6 = self.ipv6.partition("/") if prefix6: prefix6 = int(prefix6) else: prefix6 = 64 addr6 = NM.IPAddress.new(socket.AF_INET6, addr6, prefix6) s_ip6.add_address(addr6) if self.ipv6gateway: s_ip6.props.gateway = self.ipv6gateway connection.add_setting(s_ip6) # nameservers if self.nameserver: for ns in [str.strip(i) for i in self.nameserver.split(",")]: if NM.utils_ipaddr_valid(socket.AF_INET6, ns): s_ip6.add_dns(ns) elif NM.utils_ipaddr_valid(socket.AF_INET, ns): s_ip4.add_dns(ns) else: log.error("IP address %s is not valid", ns)
def print_ap_info(ap): strength = ap.get_strength() frequency = ap.get_frequency() print "SSID: %s" % (ssid_to_utf8(ap)) print "BSSID: %s" % (ap.get_bssid()) print "Frequency: %s" % (frequency) print "Channel: %s" % (NM.utils_wifi_freq_to_channel(frequency)) print "Strength: %s %s%%" % (NM.utils_wifi_strength_bars(strength), strength) print
def popen_wait(p, timeout=None): # wait() has a timeout argument only since 3.3 if Util.python_has_version(3, 3): return p.wait(timeout) if timeout is None: return p.wait() start = NM.utils_get_timestamp_msec() while True: if p.poll() is not None: return p.returncode if start + (timeout * 1000) < NM.utils_get_timestamp_msec(): raise Exception("timeout expired") time.sleep(0.05)
def wait_state(self, expected, timeout): res, out_value, _ = NM.utils_enum_from_str(NM.DeviceState, expected) if not res: raise ValueError("invalid state '{}'".format(expected)) expected = NM.DeviceState(out_value) timeout = monotonic() + timeout while monotonic() < timeout: sleep(0.25) if self._nm_dev.get_state() == expected: break else: raise TimeoutError("state is '{}' instead of '{}'".format( self._nm_dev.get_state().value_nick, expected.value_nick))
def wait_state(self, expected, timeout): res, out_value, _ = NM.utils_enum_from_str(NM.DeviceState, expected) if not res: raise ValueError(f"invalid state '{expected}'") expected = NM.DeviceState(out_value) timeout = monotonic() + timeout while monotonic() < timeout: sleep(0.25) if self._nm_dev.get_state() == expected: break else: raise TimeoutError( f"state is '{self._nm_dev.get_state().value_nick}' instead of '{expected.value_nick}'" # pylint: disable=line-too-long )
def create_ap_actions(aps, active_ap, active_connection, adapter): # pylint: disable=too-many-locals """For each AP in a list, create the string and its attached function (activate/deactivate) """ active_ap_bssid = active_ap.get_bssid() if active_ap is not None else "" names = [ssid_to_utf8(ap) for ap in aps] max_len_name = max([len(name) for name in names]) if names else 0 secs = [ap_security(ap) for ap in aps] max_len_sec = max([len(sec) for sec in secs]) if secs else 0 ap_actions = [] for nm_ap, name, sec in zip(aps, names, secs): bars = NM.utils_wifi_strength_bars(nm_ap.get_strength()) wifi_chars = CONF.get("dmenu", "wifi_chars", fallback=False) if wifi_chars: bars = "".join([wifi_chars[i] for i, j in enumerate(bars) if j == '*']) is_active = nm_ap.get_bssid() == active_ap_bssid compact = CONF.getboolean("dmenu", "compact", fallback=False) if compact: action_name = u"{} {} {}".format(name, sec, bars) else: action_name = u"{:<{}s} {:<{}s} {}".format(name, max_len_name, sec, max_len_sec, bars) if is_active: ap_actions.append(Action(action_name, process_ap, [active_connection, True, adapter], active=True)) else: ap_actions.append(Action(action_name, process_ap, [nm_ap, False, adapter])) return ap_actions
def clone_connection(context, con_src, con_dst, flags="TO_DISK"): import gi gi.require_version('NM', '1.0') from gi.repository import GLib, NM main_loop = GLib.MainLoop() nm_client = NM.Client.new(None) con = libnm_get_connection(nm_client, con_src) nm_flags = parse_NM_settings_flags_string(NM.SettingsAddConnection2Flags, flags) con2 = NM.SimpleConnection.new_clone(con) s_con = con2.get_setting_connection() s_con.set_property(NM.SETTING_CONNECTION_ID, con_dst) s_con.set_property(NM.SETTING_CONNECTION_UUID, NM.utils_uuid_generate()) result = {} def _add_connection2_cb(cl, async_result, user_data): try: nm_client.add_connection2_finish(async_result) except Exception as e: result['error'] = e main_loop.quit() nm_client.add_connection2(con2.to_dbus(NM.ConnectionSerializationFlags.ALL), nm_flags, None, False, None, _add_connection2_cb, None) main_loop.run() if 'error' in result: raise Exception('add connection %s failed: %s' % (con_dst, result['error']))
def create_ap_actions(aps, active_ap, active_connection, adapter): # pylint: disable=too-many-locals """For each AP in a list, create the string and its attached function (activate/deactivate) """ active_ap_bssid = active_ap.get_bssid() if active_ap is not None else "" names = [ssid_to_utf8(ap) for ap in aps] max_len_name = max([len(name) for name in names]) if names else 0 secs = [ap_security(ap) for ap in aps] max_len_sec = max([len(sec) for sec in secs]) if secs else 0 ap_actions = [] for nm_ap, name, sec in zip(aps, names, secs): bars = NM.utils_wifi_strength_bars(nm_ap.get_strength()).replace( '*', '◆') is_active = nm_ap.get_bssid() == active_ap_bssid action_name = u"{:<{}s} {:<{}s} {}".format(name, max_len_name, sec, max_len_sec, bars) if is_active: ap_actions.append( Action(action_name, process_ap, [active_connection, True, adapter], active=True)) else: ap_actions.append( Action(action_name, process_ap, [nm_ap, False, adapter])) return ap_actions
def nmc_new(io_priority=GLib.PRIORITY_DEFAULT, cancellable=None): # create a NMClient instance using the async initialization # (but the function itself iterates the main context until # the initialization completes). result = [] def cb(source_object, res): try: source_object.init_finish(res) except Exception as e: result.append(e) else: result.append(None) nmc = NM.Client() nmc.init_async(io_priority, cancellable, cb) while not result: nmc.get_main_context().iteration(may_block=True) if result[0]: raise result[0] log("initialized NMClient cache") return nmc
def add_wifi_connection(info: WifiInfoMessage, callback: Optional[Callable], btn: Any, nm_client: Optional[NM.Client]): conn = NM.RemoteConnection() base = NM.SettingConnection.new() connection_name = f'{info.ssid} ({BRAND_NAME})' base.set_property(NM.SETTING_CONNECTION_ID, connection_name) conn.add_setting(base) ssid = GLib.Bytes.new(info.ssid.encode()) wireless = NM.SettingWireless.new() wireless.set_property(NM.SETTING_WIRELESS_SSID, ssid) wireless.set_property(NM.SETTING_WIRELESS_HIDDEN, info.hidden) secure = NM.SettingWirelessSecurity.new() try: key_mn = NMWifiKeyMn[info.auth_type.name] if info.auth_type else None except KeyError: pass if key_mn: secure.set_property(NM.SETTING_WIRELESS_SECURITY_KEY_MGMT, key_mn) if info.password: if key_mn == NMWifiKeyMn.WPA: secure.set_property(NM.SETTING_WIRELESS_SECURITY_PSK, info.password) elif key_mn == NMWifiKeyMn.WEP: secure.set_property(NM.SETTING_WIRELESS_SECURITY_WEP_KEY0, info.password) conn.add_setting(wireless) conn.add_setting(secure) nm_client.add_connection_async(conn, True, None, callback, btn)
def create_ap_actions(aps, active_ap, active_connection, adapter): # pylint: disable=too-many-locals """For each AP in a list, create the string and its attached function (activate/deactivate) """ active_ap_bssid = active_ap.get_bssid() if active_ap is not None else "" names = [ssid_to_utf8(ap) for ap in aps] max_len_name = max([len(name) for name in names]) if names else 0 secs = [ap_security(ap) for ap in aps] max_len_sec = max([len(sec) for sec in secs]) if secs else 0 ap_actions = [] for nm_ap, name, sec in zip(aps, names, secs): bars = NM.utils_wifi_strength_bars(nm_ap.get_strength()) is_active = nm_ap.get_bssid() == active_ap_bssid action_name = u"{:<{}s} {:<{}s} {}".format(name, max_len_name, sec, max_len_sec, bars) if is_active: ap_actions.append(Action(action_name, process_ap, [active_connection, True, adapter], active=True)) else: ap_actions.append(Action(action_name, process_ap, [nm_ap, False, adapter])) return ap_actions
def create_connection(self): conn = NM.SimpleConnection() conn_id = '%s Network' % self.device['Name'] conn_uuid = str(uuid.uuid4()) conn_sett = NM.SettingConnection(type='bluetooth', id=conn_id, uuid=conn_uuid, autoconnect=False) conn_sett_bt = NM.SettingBluetooth(type=self.conntype, bdaddr=self.bdaddr) conn.add_setting(conn_sett) conn.add_setting(conn_sett_bt) self.client.add_connection_async(conn, True, None, self._on_connection_added, conn_uuid)
def ssid_to_utf8(nm_ap): """ Convert binary ssid to utf-8 """ ssid = nm_ap.get_ssid() if not ssid: return "" ret = NM.utils_ssid_to_utf8(ssid.get_data()) return ret
def print_ap_info(ap): strength = ap.get_strength() frequency = ap.get_frequency() flags = ap.get_flags() wpa_flags = ap.get_wpa_flags() rsn_flags = ap.get_rsn_flags() print("SSID: %s" % (ssid_to_utf8(ap))) print("BSSID: %s" % (ap.get_bssid())) print("Frequency: %s" % (frequency)) print("Channel: %s" % (NM.utils_wifi_freq_to_channel(frequency))) print("Mode: %s" % (mode_to_string(ap.get_mode()))) print("Flags: %s" % (flags_to_string(flags))) print("WPA flags: %s" % (security_flags_to_string(wpa_flags))) print("RSN flags: %s" % (security_flags_to_string(rsn_flags))) print("Security: %s" % (flags_to_security(flags, wpa_flags, rsn_flags))) print("Strength: %s %s%%" % (NM.utils_wifi_strength_bars(strength), strength)) print
def ssid_to_utf8(ap): """Convert access point's binary ssid to utf-8 """ ssid = ap.get_ssid() if not ssid: return "" else: return NM.utils_ssid_to_utf8(ssid.get_data())
def print_ap_info(ap): strength = ap.get_strength() frequency = ap.get_frequency() flags = ap.get_flags() wpa_flags = ap.get_wpa_flags() rsn_flags = ap.get_rsn_flags() print "SSID: %s" % (ssid_to_utf8(ap)) print "BSSID: %s" % (ap.get_bssid()) print "Frequency: %s" % (frequency) print "Channel: %s" % (NM.utils_wifi_freq_to_channel(frequency)) print "Mode: %s" % (mode_to_string(ap.get_mode())) print "Flags: %s" % (flags_to_string(flags)) print "WPA flags: %s" % (security_flags_to_string(wpa_flags)) print "RSN flags: %s" % (security_flags_to_string(rsn_flags)) print "Security: %s" % (flags_to_security(flags, wpa_flags, rsn_flags)) print "Strength: %s %s%%" % (NM.utils_wifi_strength_bars(strength), strength) print
def ssid_to_utf8(nm_ap): """ Convert binary ssid to utf-8 """ ssid = nm_ap.get_ssid() if not ssid: return "" ret = NM.utils_ssid_to_utf8(ssid.get_data()) if sys.version_info.major < 3: return ret.decode(ENC) return ret
def print_ap_info(ap): strength = ap.get_strength() frequency = ap.get_frequency() print "SSID: %s" % (ap.get_ssid()) print "BSSID: %s" % (ap.get_bssid()) print "Frequency: %s" % (frequency) print "Channel: %s" % (NM.utils_wifi_freq_to_channel(frequency)) print "Strength: %s %s%%" % (signal_bars[(clamp(strength-5, 0, 99)+24)/25], strength) print
def connect_to_selection(self): model, iterator = self.get_selection().get_selected() if iterator is None: return parent = model.iter_parent(iterator) if parent: try: devid = model[parent][0] ssid = model[iterator][0] if model[iterator][1]: if not self.nm_client: self.nm_client = NM.Client.new() device = self.nm_client.get_device_by_path(devid) ap = self.find_ap(device, ssid) connection = NM.SimpleConnection() connection.add_setting(NM.SettingConnection( uuid=NM.utils_uuid_generate() )) connection.add_setting(NM.SettingWireless( ssid=ap.get_property("ssid") )) dialog = NMA.WifiDialog.new( self.nm_client, connection, device, ap, False ) dialog.connect("response", self.connect_dialog_cb) dialog.run() else: self.wifi_model.connect_to_ap(devid, ssid) except Exception as e: dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, "Failed to connect to wireless network" ) dialog.format_secondary_text("{}".format(e)) dialog.run() dialog.hide()
def __init__(self): self.nm = NM.Client() self.nm.init() for dev in self.nm.get_all_devices(): if isinstance(dev, NM.DeviceP2PWifi): self.dev = dev break else: raise AssertionError("No P2P Wifi device was found!")
def _ssid_to_utf8(ap): """ Convert ssid to utf8 for human readability. An SSID can contain non-printable characters, NM has a util to convert. :param: ap NMAccessPoint :return: utf8 string containing the SSID """ ssid = ap.get_ssid() if not ssid: return "" return NM.utils_ssid_to_utf8(ssid.get_data())
def nm_online_full(self, iface, timeout=60): '''Wait for NetworkManager connection to be completed (incl. IP4 & DHCP)''' gi.require_version('NM', '1.0') from gi.repository import NM for t in range(timeout): c = NM.Client.new(None) con = c.get_device_by_iface(iface).get_active_connection() if not con: self.fail('no active connection for %s by NM' % iface) flags = NM.utils_enum_to_str(NM.ActivationStateFlags, con.get_state_flags()) if "ip4-ready" in flags: break time.sleep(1) else: self.fail('timed out waiting for %s to get ready by NM' % iface)
def _update_ipv4_settings(connection, ipv4_method, ipv4_address): """Edit IPv4 settings for network manager connections.""" settings = connection.get_setting_ip4_config() if not settings: settings = nm.SettingIP4Config.new() connection.add_setting(settings) settings.set_property(nm.SETTING_IP_CONFIG_METHOD, ipv4_method) if ipv4_method == nm.SETTING_IP4_CONFIG_METHOD_MANUAL and ipv4_address: ipv4_address_int = ipv4_string_to_int(ipv4_address) ipv4_prefix = nm.utils_ip4_get_default_prefix(ipv4_address_int) address = nm.IPAddress.new(socket.AF_INET, ipv4_address, ipv4_prefix) settings.add_address(address) settings.set_property(nm.SETTING_IP_CONFIG_GATEWAY, '0.0.0.0') else: settings.clear_addresses()
def create_slave_connection(slave_type, slave_idx, slave, master, settings=None): """Create a slave NM connection for virtual connection (bond, team, bridge). :param slave_type: type of slave ("bond", "team", "bridge") :type slave_type: str :param slave_idx: index of the slave for naming :type slave_idx: int :param slave: slave's device name :type slave: str :param master: slave's master device name :type master: str :param settings: list of other settings to be added to the connection :type settings: list(NM.Setting) :return: created connection :rtype: NM.SimpleConnection """ settings = settings or [] slave_name = "%s slave %d" % (master, slave_idx) con = NM.SimpleConnection.new() s_con = NM.SettingConnection.new() s_con.props.uuid = NM.utils_uuid_generate() s_con.props.id = slave_name s_con.props.slave_type = slave_type s_con.props.master = master s_con.props.type = '802-3-ethernet' # HACK preventing NM to autoactivate the connection # The real network --onboot value (ifcfg ONBOOT) will be set later by # update_onboot s_con.props.autoconnect = False con.add_setting(s_con) s_wired = NM.SettingWired.new() con.add_setting(s_wired) for setting in settings: con.add_setting(setting) return con
def do_set(connection, data, set_gobject): print_user_data(connection, False, [d[0] for d in data], prefix = 'BEFORE: ') print('') s_u = connection.get_setting(NM.SettingUser) if s_u is None: connection.add_setting(NM.SettingUser()) s_u = connection.get_setting(NM.SettingUser) for d in data: key = d[0] val = d[1] if val is None: print(' DEL: "%s"' % (key)) else: print(' SET: "%s" = "%s"' % (key, val)) if set_gobject: d = s_u.get_property(NM.SETTING_USER_DATA) if val is None: d.pop(key, None) else: d[key] = val s_u.set_property(NM.SETTING_USER_DATA, d) else: try: s_u.set_data(key, val) except Exception as e: if val is None: print('error deleting key "%s": %s' % (key, e)) else: print('error setting key "%s" = "%s": %s' % (key, val, e)) sys.exit(1) try: connection.commit_changes(True, None) except Exception as e: print('failure to commit connection: %s' % (e)) sys.exit(1) print('') print_user_data(connection, False, [d[0] for d in data], prefix = 'AFTER: ')
def get_default_connection(iface, device_type, autoconnect=False): """Get default connection to be edited by the UI.""" connection = NM.SimpleConnection.new() s_con = NM.SettingConnection.new() s_con.props.uuid = NM.utils_uuid_generate() s_con.props.autoconnect = autoconnect s_con.props.id = iface s_con.props.interface_name = iface if device_type == NM.DeviceType.ETHERNET: s_con.props.type = "802-3-ethernet" s_wired = NM.SettingWired.new() connection.add_setting(s_wired) elif device_type == NM.DeviceType.INFINIBAND: s_con.props.type = "infiniband" s_ib = NM.SettingInfiniband.new() s_ib.props.transport_mode = "datagram" connection.add_settings(s_ib) connection.add_setting(s_con) return connection
def scan_ap(self): # todo: call internet for wifi dev nmc = NM.Client.new(None) devs = nmc.get_devices() ssids = []; dev = internet.get_active_device("wifi", self) for ap in dev.get_access_points(): ssid = ap.get_ssid() if not ssid: continue ssids.append(NM.utils_ssid_to_utf8(ap.get_ssid().get_data())) if self.ap1_ssid not in ssids: self.fail("First AP not found {0}".format(self.ap1_ssid)) if self.ap2_ssid not in ssids: self.fail("Second AP not found {0}".format(self.ap2_ssid)) self.log.debug("Both APs can be found")
def get_default_connection(iface, device_type): """Get default connection to be edited by the UI.""" connection = NM.SimpleConnection.new() s_con = NM.SettingConnection.new() s_con.props.uuid = NM.utils_uuid_generate() s_con.props.autoconnect = True s_con.props.id = iface s_con.props.interface_name = iface if device_type == NM.DeviceType.ETHERNET: s_con.props.type = "802-3-ethernet" s_wired = NM.SettingWired.new() connection.add_setting(s_wired) elif device_type == NM.DeviceType.INFINIBAND: s_con.props.type = "infiniband" s_ib = NM.SettingInfiniband.new() s_ib.props.transport_mode = "datagram" connection.add_setting(s_ib) connection.add_setting(s_con) return connection
def _update_common_settings(connection, connection_uuid, name, type_, interface, zone, ipv4_method, ipv4_address): """Create/edit basic settings for network manager connections.""" if not connection: connection = nm.SimpleConnection.new() # Connection settings = connection.get_setting_connection() if not settings: settings = nm.SettingConnection.new() connection.add_setting(settings) settings.set_property(nm.SETTING_CONNECTION_UUID, connection_uuid) settings.set_property(nm.SETTING_CONNECTION_ID, name) settings.set_property(nm.SETTING_CONNECTION_TYPE, type_) settings.set_property(nm.SETTING_CONNECTION_INTERFACE_NAME, interface) settings.set_property(nm.SETTING_CONNECTION_ZONE, zone) # IPv4 settings = connection.get_setting_ip4_config() if not settings: settings = nm.SettingIP4Config.new() connection.add_setting(settings) settings.set_property(nm.SETTING_IP_CONFIG_METHOD, ipv4_method) if ipv4_method == nm.SETTING_IP4_CONFIG_METHOD_MANUAL and ipv4_address: ipv4_address_int = ipv4_string_to_int(ipv4_address) ipv4_prefix = nm.utils_ip4_get_default_prefix(ipv4_address_int) address = nm.IPAddress.new(socket.AF_INET, ipv4_address, ipv4_prefix) settings.add_address(address) settings.set_property(nm.SETTING_IP_CONFIG_GATEWAY, '0.0.0.0') else: settings.clear_addresses() return connection
return str(val).replace('"', '"') def usage(): print("Usage: %s --gir FILE --output FILE" % sys.argv[0]) exit() parser = argparse.ArgumentParser() parser.add_argument('-g', '--gir', metavar='FILE', help='NM-1.0.gir file') parser.add_argument('-x', '--overrides', metavar='FILE', help='documentation overrides file') parser.add_argument('-o', '--output', metavar='FILE', help='output file') args = parser.parse_args() if args.gir is None or args.output is None: usage() NM.utils_init() girxml = ET.parse(args.gir).getroot() outfile = open(args.output, mode='w') basexml = girxml.find('./gi:namespace/gi:class[@name="Setting"]', ns_map) settings = girxml.findall('./gi:namespace/gi:class[@parent="Setting"]', ns_map) # Hack. Need a better way to do this ipxml = girxml.find('./gi:namespace/gi:class[@name="SettingIPConfig"]', ns_map) settings.extend(girxml.findall('./gi:namespace/gi:class[@parent="SettingIPConfig"]', ns_map)) settings = sorted(settings, key=lambda setting: setting.attrib['{%s}symbol-prefix' % ns_map['c']]) init_constants(girxml, settings) if args.overrides is not None: overrides = ET.parse(args.overrides).getroot()
def add_connection_from_ksdata(nm_client, network_data, device_name, activate=False, ifname_option_values=None): """Add NM connection created from kickstart configuration. :param network_data: kickstart configuration :type network_data: pykickstart NetworkData :param device_name: name of the device to be configured by kickstart :type device_name: str :param activate: activate the added connection :type activate: bool :param ifname_option_values: list of ifname boot option values :type ifname_option_values: list(str) """ ifname_option_values = ifname_option_values or [] added_connections = [] device_to_activate = device_name con_uuid = NM.utils_uuid_generate() con = NM.SimpleConnection.new() update_connection_ip_settings_from_ksdata(con, network_data) s_con = NM.SettingConnection.new() s_con.props.uuid = con_uuid s_con.props.id = device_name s_con.props.interface_name = device_name # HACK preventing NM to autoactivate the connection # The real network --onboot value (ifcfg ONBOOT) will be set later by # update_onboot s_con.props.autoconnect = False con.add_setting(s_con) # type "bond" if network_data.bondslaves: _update_bond_connection_from_ksdata(con, network_data) for i, slave in enumerate(network_data.bondslaves.split(","), 1): slave_con = create_slave_connection('bond', i, slave, device_name) bind_connection(nm_client, slave_con, network_data.bindto, slave) added_connections.append((slave_con, slave)) # type "team" elif network_data.teamslaves: _update_team_connection_from_ksdata(con, network_data) for i, (slave, cfg) in enumerate(network_data.teamslaves, 1): s_team_port = NM.SettingTeamPort.new() s_team_port.props.config = cfg slave_con = create_slave_connection('team', i, slave, device_name, settings=[s_team_port]) bind_connection(nm_client, slave_con, network_data.bindto, slave) added_connections.append((slave_con, slave)) # type "vlan" elif network_data.vlanid: device_to_activate = _update_vlan_connection_from_ksdata(con, network_data) # type "bridge" elif network_data.bridgeslaves: # bridge connection is autoactivated _update_bridge_connection_from_ksdata(con, network_data) for i, slave in enumerate(network_data.bridgeslaves.split(","), 1): slave_con = create_slave_connection('bridge', i, slave, device_name) bind_connection(nm_client, slave_con, network_data.bindto, slave) added_connections.append((slave_con, slave)) # type "infiniband" elif is_infiniband_device(nm_client, device_name): _update_infiniband_connection_from_ksdata(con, network_data) # type "802-3-ethernet" else: bound_mac = bound_hwaddr_of_device(nm_client, device_name, ifname_option_values) _update_ethernet_connection_from_ksdata(con, network_data, bound_mac) if bound_mac: log.debug("add connection: mac %s is bound to name %s", bound_mac, device_name) else: bind_connection(nm_client, con, network_data.bindto, device_name) # Add s390 settings if is_s390(): s390cfg = get_s390_settings(device_name) _update_wired_connection_with_s390_settings(con, s390cfg) added_connections.insert(0, (con, device_to_activate)) for con, device_name in added_connections: log.debug("add connection: %s for %s\n%s", con_uuid, device_name, con.to_dbus(NM.ConnectionSerializationFlags.NO_SECRETS)) device_to_activate = device_name if activate else None nm_client.add_connection_async(con, True, None, _connection_added_cb, device_to_activate) return added_connections
def update_connection_ip_settings_from_ksdata(connection, network_data): """Update NM connection from kickstart IP configuration in place. :param connection: existing NetworkManager connection to be updated :type connection: NM.RemoteConnection :param network_data: kickstart configuation containing the IP configuration to be applied to the connection :type network_data: pykickstart NetworkData """ # ipv4 settings if network_data.noipv4: method4 = "disabled" elif network_data.bootProto == "static": method4 = "manual" else: method4 = "auto" connection.remove_setting(NM.SettingIP4Config) s_ip4 = NM.SettingIP4Config.new() s_ip4.set_property(NM.SETTING_IP_CONFIG_METHOD, method4) if method4 == "manual": prefix4 = netmask2prefix(network_data.netmask) addr4 = NM.IPAddress.new(socket.AF_INET, network_data.ip, prefix4) s_ip4.add_address(addr4) if network_data.gateway: s_ip4.props.gateway = network_data.gateway connection.add_setting(s_ip4) # ipv6 settings if network_data.noipv6: method6 = "ignore" elif not network_data.ipv6 or network_data.ipv6 == "auto": method6 = "auto" elif network_data.ipv6 == "dhcp": method6 = "dhcp" else: method6 = "manual" connection.remove_setting(NM.SettingIP6Config) s_ip6 = NM.SettingIP6Config.new() s_ip6.set_property(NM.SETTING_IP_CONFIG_METHOD, method6) if method6 == "manual": addr6, _slash, prefix6 = network_data.ipv6.partition("/") if prefix6: prefix6 = int(prefix6) else: prefix6 = 64 addr6 = NM.IPAddress.new(socket.AF_INET6, addr6, prefix6) s_ip6.add_address(addr6) if network_data.ipv6gateway: s_ip6.props.gateway = network_data.ipv6gateway connection.add_setting(s_ip6) # nameservers if network_data.nameserver: for ns in [str.strip(i) for i in network_data.nameserver.split(",")]: if NM.utils_ipaddr_valid(socket.AF_INET6, ns): s_ip6.add_dns(ns) elif NM.utils_ipaddr_valid(socket.AF_INET, ns): s_ip4.add_dns(ns) else: log.error("IP address %s is not valid", ns)
def ssid_to_utf8(ap): ssid = ap.get_ssid() if not ssid: return "" return NM.utils_ssid_to_utf8(ap.get_ssid().get_data())
basexml = girxml.find('./gi:namespace/gi:class[@name="Setting"]', ns_map) settings = girxml.findall('./gi:namespace/gi:class[@parent="Setting"]', ns_map) # HACK: Need a better way to do this ipxml = girxml.find('./gi:namespace/gi:class[@name="SettingIPConfig"]', ns_map) settings.extend(girxml.findall('./gi:namespace/gi:class[@parent="SettingIPConfig"]', ns_map)) settings = sorted(settings, key=lambda setting: setting.attrib['{%s}symbol-prefix' % ns_map['c']]) # generate setting keys constants = {} outfile.write("---\n") outfile.write("NMSettings:\n") for settingxml in settings: if 'abstract' in settingxml.attrib: continue new_func = NM.__getattr__(settingxml.attrib['name']) setting = new_func() setting_capcase_name = settingxml.attrib['name'] setting_name_prefix = "NM_" + settingxml.attrib['{%s}symbol-prefix' % ns_map['c']].upper().replace('-', '_') outfile.write(" - SettingClass: %s\n" % settingxml.attrib['name']) setting_name = "%s_SETTING_NAME" % setting_name_prefix outfile.write(" Name: %s\n" % setting_name) outfile.write(" Value: %s\n" % setting.props.name) outfile.write(" Keys:\n") constants[setting_name]=setting.props.name setting_properties = { prop.name: prop for prop in GObject.list_properties(setting) } properties = sorted(set(setting_properties.keys())) for prop in properties: