Ejemplo n.º 1
0
def down(interface, iface_type=None):
    '''
    Disable the specified interface

    :param str interface: interface label
    :return: True if the service was disabled, otherwise an exception will be thrown.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' ip.down interface-label
    '''
    service = _interface_to_service(interface)
    if not service:
        raise salt.exceptions.CommandExecutionError(
            'Invalid interface name: {0}'.format(interface))
    if _connected(service):
        service = pyconnman.ConnService(_add_path(service))
        try:
            state = service.disconnect()
            return state is None
        except Exception as exc:
            raise salt.exceptions.CommandExecutionError(
                'Couldn\'t disable service: {0}\n'.format(service))
    return True
Ejemplo n.º 2
0
def _connected(service):
    """
    Verify if a connman service is connected
    """
    state = pyconnman.ConnService(os.path.join(SERVICE_PATH,
                                               service)).get_property("State")
    return state == "online" or state == "ready"
Ejemplo n.º 3
0
def _connected(service):
    '''
    Verify if a connman service is connected
    '''
    state = pyconnman.ConnService(os.path.join(SERVICE_PATH,
                                               service)).get_property('State')
    return state == 'online' or state == 'ready'
Ejemplo n.º 4
0
def _change_state(interface, new_state):
    '''
    Enable or disable an interface

    Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.

    :param interface: interface label
    :param new_state: up or down
    :return: True if the service was enabled, otherwise an exception will be thrown.
    :rtype: bool
    '''
    if __grains__['lsb_distrib_id'] == 'nilrt':
        return _change_state_legacy(interface, new_state)
    service = _interface_to_service(interface)
    if not service:
        raise salt.exceptions.CommandExecutionError(
            'Invalid interface name: {0}'.format(interface))
    connected = _connected(service)
    if (not connected and new_state == 'up') or (connected
                                                 and new_state == 'down'):
        service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
        try:
            state = service.connect(
            ) if new_state == 'up' else service.disconnect()
            return state is None
        except Exception:
            raise salt.exceptions.CommandExecutionError(
                'Couldn\'t {0} service: {1}\n'.format(
                    'enable' if new_state == 'up' else 'disable', service))
    return True
Ejemplo n.º 5
0
def set_dhcp_linklocal_all(interface):
    '''
    Configure specified adapter to use DHCP with linklocal fallback

    :param str interface: interface label
    :return: True if the settings ware applied, otherwise an exception will be thrown.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' ip.set_dhcp_linklocal_all interface-label
    '''
    service = _interface_to_service(interface)
    if not service:
        raise salt.exceptions.CommandExecutionError(
            'Invalid interface name: {0}'.format(interface))
    service = pyconnman.ConnService(_add_path(service))
    ipv4 = service.get_property('IPv4.Configuration')
    ipv4['Method'] = dbus.String('dhcp', variant_level=1)
    ipv4['Address'] = dbus.String('', variant_level=1)
    ipv4['Netmask'] = dbus.String('', variant_level=1)
    ipv4['Gateway'] = dbus.String('', variant_level=1)
    try:
        service.set_property('IPv4.Configuration', ipv4)
        service.set_property('Nameservers.Configuration',
                             [''])  # reset nameservers list
    except Exception as exc:
        raise salt.exceptions.CommandExecutionError(
            'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.
            format(service, exc))
    return True
Ejemplo n.º 6
0
def set_static_all(interface, address, netmask, gateway, nameservers):
    '''
    Configure specified adapter to use ipv4 manual settings

    :param str interface: interface label
    :param str address: ipv4 address
    :param str netmask: ipv4 netmask
    :param str gateway: ipv4 gateway
    :param str nameservers: list of nameservers servers separated by spaces
    :return: True if the settings were applied, otherwise an exception will be thrown.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' ip.set_static_all interface-label address netmask gateway nameservers
    '''
    service = _interface_to_service(interface)
    if not service:
        raise salt.exceptions.CommandExecutionError(
            'Invalid interface name: {0}'.format(interface))
    validate, msg = _validate_ipv4([address, netmask, gateway])
    if not validate:
        raise salt.exceptions.CommandExecutionError(msg)
    if nameservers:
        validate, msg = _space_delimited_list(nameservers)
        if not validate:
            raise salt.exceptions.CommandExecutionError(msg)
        if not isinstance(nameservers, list):
            nameservers = nameservers.split(' ')
    service = _interface_to_service(interface)
    if not service:
        if interface in pyiface.getIfaces():
            return _configure_static_interface(
                interface, **{
                    'ip': address,
                    'dns': ','.join(nameservers),
                    'netmask': netmask,
                    'gateway': gateway
                })
        raise salt.exceptions.CommandExecutionError(
            'Invalid interface name: {0}'.format(interface))
    service = pyconnman.ConnService(_add_path(service))
    ipv4 = service.get_property('IPv4.Configuration')
    ipv4['Method'] = dbus.String('manual', variant_level=1)
    ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1)
    ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1)
    ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1)
    try:
        service.set_property('IPv4.Configuration', ipv4)
        if nameservers:
            service.set_property(
                'Nameservers.Configuration',
                [dbus.String('{0}'.format(d)) for d in nameservers])
    except Exception as exc:
        raise salt.exceptions.CommandExecutionError(
            'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.
            format(service, exc))
    return True
Ejemplo n.º 7
0
 def dissconnect(self, services_id):
     service_path = self.path + services_id
     try:
         service = pyconnman.ConnService(service_path)
         service.remove()
     except dbus.exceptions.DBusException:
         print 'Unable to complete:', sys.exc_info()
Ejemplo n.º 8
0
def down(interface, iface_type=None):  # pylint: disable=unused-argument
    '''
    Disable the specified interface

    :param str interface: interface label
    :return: True if the service was disabled, otherwise an exception will be thrown.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' ip.down interface-label
    '''
    if __grains__['lsb_distrib_id'] == 'nilrt':
        out = __salt__['cmd.run_all']('ip link set {0} down'.format(interface))
        if out['retcode'] != 0:
            msg = 'Couldn\'t disable interface {0}. Error: {1}'.format(
                interface, out['stderr'])
            raise salt.exceptions.CommandExecutionError(msg)
        return True
    service = _interface_to_service(interface)
    if not service:
        raise salt.exceptions.CommandExecutionError(
            'Invalid interface name: {0}'.format(interface))
    if _connected(service):
        service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
        try:
            state = service.disconnect()
            return state is None
        except Exception:
            raise salt.exceptions.CommandExecutionError(
                'Couldn\'t disable service: {0}\n'.format(service))
    return True
Ejemplo n.º 9
0
def _get_service_info(service):
    '''
    return details about given connman service
    '''
    service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
    data = {
        'label': service,
        'wireless': service_info.get_property('Type') == 'wifi',
        'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']),
        'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address'])
    }

    state = service_info.get_property('State')
    if state == 'ready' or state == 'online':
        data['up'] = True
        data['ipv4'] = {
            'gateway': '0.0.0.0'
        }
        ipv4 = 'IPv4'
        if service_info.get_property('IPv4')['Method'] == 'manual':
            ipv4 += '.Configuration'
        ipv4_info = service_info.get_property(ipv4)
        for info in ['Method', 'Address', 'Netmask', 'Gateway']:
            value = ipv4_info.get(info)
            if value is None:
                log.warning('Unable to get IPv4 %s for service %s\n', info, service)
                continue
            if info == 'Method':
                info = 'requestmode'
                if value == 'dhcp':
                    value = 'dhcp_linklocal'
                elif value in ('manual', 'fixed'):
                    value = 'static'
            data['ipv4'][info.lower()] = six.text_type(value)

        ipv6_info = service_info.get_property('IPv6')
        for info in ['Address', 'Prefix', 'Gateway']:
            value = ipv6_info.get(info)
            if value is None:
                log.warning('Unable to get IPv6 %s for service %s\n', info, service)
                continue
            data['ipv6'][info.lower()] = [six.text_type(value)]

        nameservers = []
        for nameserver_prop in service_info.get_property('Nameservers'):
            nameservers.append(six.text_type(nameserver_prop))
        data['ipv4']['dns'] = nameservers
    else:
        data['up'] = False
        data['ipv4'] = {
            'requestmode': 'disabled'
        }

    data['ipv4']['supportedrequestmodes'] = [
        'dhcp_linklocal',
        'disabled',
        'static'
    ]
    return data
Ejemplo n.º 10
0
def _interface_to_service(iface):
    '''
    returns the coresponding service to given interface if exists, otherwise return None
    '''
    for _service in _get_services():
        service_info = pyconnman.ConnService(_add_path(_service))
        if service_info.get_property('Ethernet')['Interface'] == iface:
            return _service
    return None
Ejemplo n.º 11
0
def _get_service_info(service):
    """
    return details about given connman service
    """
    service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
    data = {
        "label":
        service,
        "wireless":
        service_info.get_property("Type") == "wifi",
        "connectionid":
        six.text_type(service_info.get_property("Ethernet")["Interface"]),
        "hwaddr":
        six.text_type(service_info.get_property("Ethernet")["Address"]),
    }

    state = service_info.get_property("State")
    if state == "ready" or state == "online":
        data["up"] = True
        data["ipv4"] = {"gateway": "0.0.0.0"}
        ipv4 = "IPv4"
        if service_info.get_property("IPv4")["Method"] == "manual":
            ipv4 += ".Configuration"
        ipv4_info = service_info.get_property(ipv4)
        for info in ["Method", "Address", "Netmask", "Gateway"]:
            value = ipv4_info.get(info)
            if value is None:
                log.warning("Unable to get IPv4 %s for service %s\n", info,
                            service)
                continue
            if info == "Method":
                info = "requestmode"
                if value == "dhcp":
                    value = "dhcp_linklocal"
                elif value in ("manual", "fixed"):
                    value = "static"
            data["ipv4"][info.lower()] = six.text_type(value)

        ipv6_info = service_info.get_property("IPv6")
        for info in ["Address", "Prefix", "Gateway"]:
            value = ipv6_info.get(info)
            if value is None:
                log.warning("Unable to get IPv6 %s for service %s\n", info,
                            service)
                continue
            data["ipv6"][info.lower()] = [six.text_type(value)]

        nameservers = []
        for nameserver_prop in service_info.get_property("Nameservers"):
            nameservers.append(six.text_type(nameserver_prop))
        data["ipv4"]["dns"] = nameservers
    else:
        data["up"] = False

    if "ipv4" in data:
        data["ipv4"]["supportedrequestmodes"] = ["static", "dhcp_linklocal"]
    return data
Ejemplo n.º 12
0
def _get_service_info(service):
    '''
    return details about given connman service
    '''
    service_info = pyconnman.ConnService(_add_path(service))
    data = {
        'label':
        service,
        'wireless':
        service_info.get_property('Type') == 'wifi',
        'connectionid':
        six.text_type(service_info.get_property('Ethernet')['Interface']),
        'hwaddr':
        six.text_type(service_info.get_property('Ethernet')['Address'])
    }

    state = service_info.get_property('State')
    if state == 'ready' or state == 'online':
        data['up'] = True
        data['ipv4'] = {'gateway': '0.0.0.0'}
        ipv4 = 'IPv4'
        if service_info.get_property('IPv4')['Method'] == 'manual':
            ipv4 += '.Configuration'
        ipv4Info = service_info.get_property(ipv4)
        for info in ['Method', 'Address', 'Netmask', 'Gateway']:
            try:
                value = ipv4Info[info]
                if info == 'Method':
                    info = 'requestmode'
                    if value == 'dhcp':
                        value = 'dhcp_linklocal'
                    elif value == 'manual':
                        value = 'static'
                data['ipv4'][info.lower()] = six.text_type(value)
            except Exception as exc:
                log.warning('Unable to get IPv4 %s for service %s\n', info,
                            service)

        ipv6Info = service_info.get_property('IPv6')
        for info in ['Address', 'Prefix', 'Gateway']:
            try:
                value = ipv6Info[info]
                data['ipv6'][info.lower()] = [six.text_type(value)]
            except Exception as exc:
                log.warning('Unable to get IPv6 %s for service %s\n', info,
                            service)

        nameservers = []
        for x in service_info.get_property('Nameservers'):
            nameservers.append(six.text_type(x))
        data['ipv4']['dns'] = nameservers
    else:
        data['up'] = False

    if 'ipv4' in data:
        data['ipv4']['supportedrequestmodes'] = ['static', 'dhcp_linklocal']
    return data
Ejemplo n.º 13
0
def _interface_to_service(iface):
    """
    returns the coresponding service to given interface if exists, otherwise return None
    """
    for _service in _get_services():
        service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service))
        if service_info.get_property("Ethernet")["Interface"] == iface:
            return _service
    return None
Ejemplo n.º 14
0
 def set_ipv4_dhcp(self, Method, net_name):
     cnt, list_services_info = self.get_services_info()
     for i in range(cnt):
         if (list_services_info[i * 8 + 3] == net_name):
             service_py = pyconnman.ConnService(list_services_info[i * 8 +
                                                                   0])
             name = "IPv4.Configuration"
             value22 = {
                 dbus.String(u'Method'): dbus.String(Method,
                                                     variant_level=1)
             }
             service_py.set_property(name, value22)
Ejemplo n.º 15
0
def service_rm(args):
    if (len(args)):
        service_path = args.pop(0)
    else:
        print('Error: Must specify service path')
        return

    try:
        service = pyconnman.ConnService(service_path)
        service.remove()
    except dbus.exceptions.DBusException:
        print('Unable to complete:', sys.exc_info())
Ejemplo n.º 16
0
 def test_service_basic(self):
     manager = pyconnman.ConnManager()
     services = manager.get_services()
     serv = pyconnman.ConnService(services[0][0])
     print "Serv:", serv
     print '========================================================='
     serv.connect()
     serv.disconnect()
     serv.move_before('a service')
     serv.move_after('a service')
     serv.reset_counters()
     serv.remove()
     serv.clear_property('a property')
Ejemplo n.º 17
0
def service_info(args):
    if (len(args)):
        service_path = args.pop(0)
    else:
        print 'Error: Must specify service path'
        return

    try:
        service = pyconnman.ConnService(service_path)
        print '========================================================='
        print service
    except dbus.exceptions.DBusException:
        print 'Unable to complete:', sys.exc_info()
Ejemplo n.º 18
0
def service_set(args):
    if (len(args) >= 3):
        service_path = args.pop(0)
        name = args.pop(0)
        value = args.pop(0)
    else:
        print('Error: Requires service path, property name and value')
        return

    try:
        service = pyconnman.ConnService(service_path)
        service.set_property(name, value)
    except dbus.exceptions.DBusException:
        print('Unable to complete:', sys.exc_info())
Ejemplo n.º 19
0
def set_dhcp_linklocal_all(interface):
    """
    Configure specified adapter to use DHCP with linklocal fallback

    Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.

    :param str interface: interface label
    :return: True if the settings were applied, otherwise an exception will be thrown.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' ip.set_dhcp_linklocal_all interface-label
    """
    if __grains__["lsb_distrib_id"] == "nilrt":
        initial_mode = _get_adapter_mode_info(interface)
        _save_config(interface, "Mode", "TCPIP")
        _save_config(interface, "dhcpenabled", "1")
        _save_config(interface, "linklocalenabled", "1")
        if initial_mode == "ethercat":
            __salt__["system.set_reboot_required_witnessed"]()
        else:
            _restart(interface)
        return True
    service = _interface_to_service(interface)
    if not service:
        raise salt.exceptions.CommandExecutionError(
            "Invalid interface name: {0}".format(interface)
        )
    service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
    ipv4 = service.get_property("IPv4.Configuration")
    ipv4["Method"] = dbus.String("dhcp", variant_level=1)
    ipv4["Address"] = dbus.String("", variant_level=1)
    ipv4["Netmask"] = dbus.String("", variant_level=1)
    ipv4["Gateway"] = dbus.String("", variant_level=1)
    try:
        service.set_property("IPv4.Configuration", ipv4)
        service.set_property(
            "Nameservers.Configuration", [""]
        )  # reset nameservers list
    except Exception as exc:  # pylint: disable=broad-except
        exc_msg = "Couldn't set dhcp linklocal for service: {0}\nError: {1}\n".format(
            service, exc
        )
        raise salt.exceptions.CommandExecutionError(exc_msg)
    return True
Ejemplo n.º 20
0
def set_dhcp_linklocal_all(interface):
    '''
    Configure specified adapter to use DHCP with linklocal fallback

    Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.

    :param str interface: interface label
    :return: True if the settings were applied, otherwise an exception will be thrown.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' ip.set_dhcp_linklocal_all interface-label
    '''
    if __grains__['lsb_distrib_id'] == 'nilrt':
        initial_mode = _get_adapter_mode_info(interface)
        _save_config(interface, 'Mode', 'TCPIP')
        _save_config(interface, 'dhcpenabled', '1')
        _save_config(interface, 'linklocalenabled', '1')
        if initial_mode == 'ethercat':
            __salt__['system.set_reboot_required_witnessed']()
        else:
            _restart(interface)
        return True
    service = _interface_to_service(interface)
    if not service:
        if interface in map(lambda x: x.name, pyiface.getIfaces()):
            return _enable_dhcp(interface)
        raise salt.exceptions.CommandExecutionError(
            'Invalid interface name: {0}'.format(interface))
    service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
    ipv4 = service.get_property('IPv4.Configuration')
    ipv4['Method'] = dbus.String('dhcp', variant_level=1)
    ipv4['Address'] = dbus.String('', variant_level=1)
    ipv4['Netmask'] = dbus.String('', variant_level=1)
    ipv4['Gateway'] = dbus.String('', variant_level=1)
    try:
        service.set_property('IPv4.Configuration', ipv4)
        service.set_property('Nameservers.Configuration',
                             [''])  # reset nameservers list
    except Exception as exc:
        exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(
            service, exc)
        raise salt.exceptions.CommandExecutionError(exc_msg)
    return True
Ejemplo n.º 21
0
def _change_state(interface, new_state):
    """
    Enable or disable an interface

    Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.

    :param interface: interface label
    :param new_state: up or down
    :return: True if the service was enabled, otherwise an exception will be thrown.
    :rtype: bool
    """
    if __grains__["lsb_distrib_id"] == "nilrt":
        initial_mode = _get_adapter_mode_info(interface)
        _save_config(interface, "Mode", "TCPIP")
        if initial_mode == "ethercat":
            __salt__["system.set_reboot_required_witnessed"]()
        else:
            out = __salt__["cmd.run_all"](
                "ip link set {0} {1}".format(interface, new_state)
            )
            if out["retcode"] != 0:
                msg = "Couldn't {0} interface {1}. Error: {2}".format(
                    "enable" if new_state == "up" else "disable",
                    interface,
                    out["stderr"],
                )
                raise salt.exceptions.CommandExecutionError(msg)
        return True
    service = _interface_to_service(interface)
    if not service:
        raise salt.exceptions.CommandExecutionError(
            "Invalid interface name: {0}".format(interface)
        )
    connected = _connected(service)
    if (not connected and new_state == "up") or (connected and new_state == "down"):
        service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
        try:
            state = service.connect() if new_state == "up" else service.disconnect()
            return state is None
        except Exception:  # pylint: disable=broad-except
            raise salt.exceptions.CommandExecutionError(
                "Couldn't {0} service: {1}\n".format(
                    "enable" if new_state == "up" else "disable", service
                )
            )
    return True
Ejemplo n.º 22
0
def service_get(args):
    if (len(args)):
        service_path = args.pop(0)
        if (len(args)):
            name = args.pop(0)
        else:
            name = None
    else:
        print('Error: Must specify service path')
        return

    print('=========================================================')

    try:
        service = pyconnman.ConnService(service_path)
        print(service.get_property(name=name))
    except dbus.exceptions.DBusException:
        print('Unable to complete:', sys.exc_info())
Ejemplo n.º 23
0
def _change_state(interface, new_state):
    '''
    Enable or disable an interface

    Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.

    :param interface: interface label
    :param new_state: up or down
    :return: True if the service was enabled, otherwise an exception will be thrown.
    :rtype: bool
    '''
    if __grains__['lsb_distrib_id'] == 'nilrt':
        initial_mode = _get_adapter_mode_info(interface)
        _save_config(interface, 'Mode',
                     'TCPIP' if new_state == 'up' else 'Disabled')
        if initial_mode == 'ethercat':
            __salt__['system.set_reboot_required_witnessed']()
        else:
            out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(
                interface, new_state))
            if out['retcode'] != 0:
                msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format(
                    'enable' if new_state == 'up' else 'disable', interface,
                    out['stderr'])
                raise salt.exceptions.CommandExecutionError(msg)
        return True
    service = _interface_to_service(interface)
    if not service:
        raise salt.exceptions.CommandExecutionError(
            'Invalid interface name: {0}'.format(interface))
    connected = _connected(service)
    if (not connected and new_state == 'up') or (connected
                                                 and new_state == 'down'):
        service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
        try:
            state = service.connect(
            ) if new_state == 'up' else service.disconnect()
            return state is None
        except Exception:
            raise salt.exceptions.CommandExecutionError(
                'Couldn\'t {0} service: {1}\n'.format(
                    'enable' if new_state == 'up' else 'disable', service))
    return True
Ejemplo n.º 24
0
    def set_ipv4(self, Netmask, Gateway, Method, Address, net_name):
        cnt, list_services_info = self.get_services_info()

        for i in range(cnt):
            if (list_services_info[i * 8 + 3] == net_name):
                service_py = pyconnman.ConnService(list_services_info[i * 8 +
                                                                      0])
                name = "IPv4.Configuration"
                value22 = {
                    dbus.String(u'Netmask'): dbus.String(Netmask,
                                                         variant_level=1),
                    dbus.String(u'Gateway'): dbus.String(Gateway,
                                                         variant_level=1),
                    dbus.String(u'Method'): dbus.String(Method,
                                                        variant_level=1),
                    dbus.String(u'Address'): dbus.String(Address,
                                                         variant_level=1)
                }
                service_py.set_property(name, value22)
Ejemplo n.º 25
0
def wifi_connect(ssid, password):
    try:
        wifi_enable()
        path = wifi_service_path(ssid)
        if (path is None):
            return False
        print path + ' [' + ssid + ']'
        agent_path = '/bwsetup/agent'
        agent = pyconnman.SimpleWifiAgent(agent_path)
        agent.set_service_params(path, None, ssid, None, None, None, password,
                                 None)
        pyconnman.ConnManager().register_agent(agent_path)
        try:
            service = pyconnman.ConnService(path)
            service.set_property('autoconnect', 'yes')
            service.set_property('ipv4', 'dhcp')
            service.connect()
        except Exception, e:
            print e
        pyconnman.ConnManager().unregister_agent(agent_path)
        return True
Ejemplo n.º 26
0
def set_dhcp_linklocal_all(interface):
    '''
    Configure specified adapter to use DHCP with linklocal fallback

    :param str interface: interface label
    :return: True if the settings ware applied, otherwise an exception will be thrown.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' ip.set_dhcp_linklocal_all interface-label
    '''
    if __grains__['lsb_distrib_id'] == 'nilrt':
        _persist_config(interface, 'dhcpenabled', '1')
        _persist_config(interface, 'linklocalenabled', '1')
        disable(interface)
        enable(interface)
        return True
    service = _interface_to_service(interface)
    if not service:
        raise salt.exceptions.CommandExecutionError(
            'Invalid interface name: {0}'.format(interface))
    service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
    ipv4 = service.get_property('IPv4.Configuration')
    ipv4['Method'] = dbus.String('dhcp', variant_level=1)
    ipv4['Address'] = dbus.String('', variant_level=1)
    ipv4['Netmask'] = dbus.String('', variant_level=1)
    ipv4['Gateway'] = dbus.String('', variant_level=1)
    try:
        service.set_property('IPv4.Configuration', ipv4)
        service.set_property('Nameservers.Configuration',
                             [''])  # reset nameservers list
    except Exception as exc:
        exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(
            service, exc)
        raise salt.exceptions.CommandExecutionError(exc_msg)
    return True
Ejemplo n.º 27
0
def set_static_all(interface, address, netmask, gateway, nameservers):
    """
    Configure specified adapter to use ipv4 manual settings

    Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.

    :param str interface: interface label
    :param str address: ipv4 address
    :param str netmask: ipv4 netmask
    :param str gateway: ipv4 gateway
    :param str nameservers: list of nameservers servers separated by spaces
    :return: True if the settings were applied, otherwise an exception will be thrown.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' ip.set_static_all interface-label address netmask gateway nameservers
    """
    validate, msg = _validate_ipv4([address, netmask, gateway])
    if not validate:
        raise salt.exceptions.CommandExecutionError(msg)
    validate, msg = _space_delimited_list(nameservers)
    if not validate:
        raise salt.exceptions.CommandExecutionError(msg)
    if not isinstance(nameservers, list):
        nameservers = nameservers.split(" ")
    if __grains__["lsb_distrib_id"] == "nilrt":
        initial_mode = _get_adapter_mode_info(interface)
        _save_config(interface, "Mode", "TCPIP")
        _save_config(interface, "dhcpenabled", "0")
        _save_config(interface, "linklocalenabled", "0")
        _save_config(interface, "IP_Address", address)
        _save_config(interface, "Subnet_Mask", netmask)
        _save_config(interface, "Gateway", gateway)
        if nameservers:
            _save_config(interface, "DNS_Address", nameservers[0])
        if initial_mode == "ethercat":
            __salt__["system.set_reboot_required_witnessed"]()
        else:
            _restart(interface)
        return True
    service = _interface_to_service(interface)
    if not service:
        if interface in pyiface.getIfaces():
            return _configure_static_interface(
                interface,
                **{
                    "ip": address,
                    "dns": ",".join(nameservers),
                    "netmask": netmask,
                    "gateway": gateway,
                }
            )
        raise salt.exceptions.CommandExecutionError(
            "Invalid interface name: {0}".format(interface)
        )
    service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
    ipv4 = service.get_property("IPv4.Configuration")
    ipv4["Method"] = dbus.String("manual", variant_level=1)
    ipv4["Address"] = dbus.String("{0}".format(address), variant_level=1)
    ipv4["Netmask"] = dbus.String("{0}".format(netmask), variant_level=1)
    ipv4["Gateway"] = dbus.String("{0}".format(gateway), variant_level=1)
    try:
        service.set_property("IPv4.Configuration", ipv4)
        service.set_property(
            "Nameservers.Configuration",
            [dbus.String("{0}".format(d)) for d in nameservers],
        )
    except Exception as exc:  # pylint: disable=broad-except
        exc_msg = "Couldn't set manual settings for service: {0}\nError: {1}\n".format(
            service, exc
        )
        raise salt.exceptions.CommandExecutionError(exc_msg)
    return True
Ejemplo n.º 28
0
        print '* clean iptables'
        subprocess.call(['/app/wifi/setup-iptables.sh', 'R'])

        tethering = tech.get_property('Tethering')
        print '* currently tethering? ', tethering

        if tethering:
            print '* disable tethering'
            tech.set_property('Tethering', False)

            # TODO: change this hardcoded sleep time
            print '* sleeping for 15s'
            time.sleep(15)

        print '* linking to service: ', service_path
        service = pyconnman.ConnService(service_path)

        print '* connection state:', service.State

        if service.State != 'ready':
            connected = service.connect()

            print '* connect returned: ', connected

            print '* connection state after connect:', service.State

            #TODO: only save if succesful
            # save credentials
            if connected == None:
                print '* connected succefully, saving credentials in /data/creds.p'
                with open('/data/creds.p', 'wb') as f:
Ejemplo n.º 29
0
def _connected(service):
    '''
    Verify if a connman service is connected
    '''
    state = pyconnman.ConnService(_add_path(service)).get_property('State')
    return state == 'online' or state == 'ready'
Ejemplo n.º 30
0
def set_static_all(interface, address, netmask, gateway, nameservers):
    '''
    Configure specified adapter to use ipv4 manual settings

    Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.

    :param str interface: interface label
    :param str address: ipv4 address
    :param str netmask: ipv4 netmask
    :param str gateway: ipv4 gateway
    :param str nameservers: list of nameservers servers separated by spaces
    :return: True if the settings were applied, otherwise an exception will be thrown.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' ip.set_static_all interface-label address netmask gateway nameservers
    '''
    validate, msg = _validate_ipv4([address, netmask, gateway])
    if not validate:
        raise salt.exceptions.CommandExecutionError(msg)
    validate, msg = _space_delimited_list(nameservers)
    if not validate:
        raise salt.exceptions.CommandExecutionError(msg)
    if not isinstance(nameservers, list):
        nameservers = nameservers.split(' ')
    if __grains__['lsb_distrib_id'] == 'nilrt':
        initial_mode = _get_adapter_mode_info(interface)
        _save_config(interface, 'Mode', 'TCPIP')
        _save_config(interface, 'dhcpenabled', '0')
        _save_config(interface, 'linklocalenabled', '0')
        _save_config(interface, 'IP_Address', address)
        _save_config(interface, 'Subnet_Mask', netmask)
        _save_config(interface, 'Gateway', gateway)
        if nameservers:
            _save_config(interface, 'DNS_Address', nameservers[0])
        if initial_mode == 'ethercat':
            __salt__['system.set_reboot_required_witnessed']()
        else:
            _restart(interface)
        return True
    service = _interface_to_service(interface)
    if not service:
        if interface in pyiface.getIfaces():
            return _configure_static_interface(
                interface, **{
                    'ip': address,
                    'dns': ','.join(nameservers),
                    'netmask': netmask,
                    'gateway': gateway
                })
        raise salt.exceptions.CommandExecutionError(
            'Invalid interface name: {0}'.format(interface))
    service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
    ipv4 = service.get_property('IPv4.Configuration')
    ipv4['Method'] = dbus.String('manual', variant_level=1)
    ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1)
    ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1)
    ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1)
    try:
        service.set_property('IPv4.Configuration', ipv4)
        service.set_property(
            'Nameservers.Configuration',
            [dbus.String('{0}'.format(d)) for d in nameservers])
    except Exception as exc:
        exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(
            service, exc)
        raise salt.exceptions.CommandExecutionError(exc_msg)
    return True