Example #1
0
def ip_host(value, options=None, version=None):
    '''
    Returns the interfaces IP address, e.g.: 192.168.0.1/28.
    '''
    ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
    if not ipaddr_filter_out:
        return
    if not isinstance(value, (list, tuple, types.GeneratorType)):
        return str(ipaddress.ip_interface(ipaddr_filter_out[0]))
    return [str(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out]
Example #2
0
def _subnets(proto='inet', interfaces_=None):
    '''
    Returns a list of subnets to which the host belongs
    '''
    if interfaces_ is None:
        ifaces = interfaces()
    elif isinstance(interfaces_, list):
        ifaces = {}
        for key, value in six.iteritems(interfaces()):
            if key in interfaces_:
                ifaces[key] = value
    else:
        ifaces = {interfaces_: interfaces().get(interfaces_, {})}

    ret = set()

    if proto == 'inet':
        subnet = 'netmask'
    elif proto == 'inet6':
        subnet = 'prefixlen'
    else:
        log.error('Invalid proto {0} calling subnets()'.format(proto))
        return

    for ip_info in six.itervalues(ifaces):
        addrs = ip_info.get(proto, [])
        addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto])

        for intf in addrs:
            intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet]))
            if not intf.is_loopback:
                ret.add(intf.network)
    return [str(net) for net in sorted(ret)]
Example #3
0
def _get_proxy_details(api_url, minion_id, primary_ip, platform_id, headers):
    log.debug(
        'Retrieving proxy details for "%s"',
        minion_id,
    )
    platform_url = "{api_url}/{app}/{endpoint}/{id}/".format(
        api_url=api_url, app="dcim", endpoint="platforms", id=platform_id)
    platform_ret = salt.utils.http.query(platform_url,
                                         header_dict=headers,
                                         decode=True)
    # Check status code for API call
    if "error" in platform_ret:
        log.error(
            "Unable to proxy details for %s, status code: %d, error %s",
            minion_id,
            platform_ret["status"],
            platform_ret["error"],
        )
    else:
        # Assign results from API call to "proxy" key if the platform has a
        # napalm_driver defined.
        napalm_driver = platform_ret["dict"].get("napalm_driver")
        if napalm_driver:
            proxy = {
                "host": str(ipaddress.ip_interface(primary_ip).ip),
                "driver": napalm_driver,
                "proxytype": "napalm",
            }
            return proxy
Example #4
0
def ip_host(value, options=None, version=None):
    '''
    Returns the interfaces IP address, e.g.: 192.168.0.1/28.
    '''
    ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
    if not ipaddr_filter_out:
        return
    return [ipaddress.ip_interface(ip_a) for ip_a in ipaddr_filter_out]
Example #5
0
def ip_host(value, options=None, version=None):
    '''
    Returns the interfaces IP address, e.g.: 192.168.0.1/28.
    '''
    ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
    if not ipaddr_filter_out:
        return
    return [ipaddress.ip_interface(ip_a) for ip_a in ipaddr_filter_out]
Example #6
0
File: dns.py Project: yvwulei/salt
def spf_rec(rdata):
    '''
    Validate and parse DNS record data for SPF record(s)
    :param rdata: DNS record data
    :return: dict w/fields
    '''
    spf_fields = rdata.split(' ')
    if not spf_fields.pop(0).startswith('v=spf'):
        raise ValueError('Not an SPF record')

    res = OrderedDict()
    mods = set()
    for mech_spec in spf_fields:
        if mech_spec.startswith(('exp', 'redirect')):
            # It's a modifier
            mod, val = mech_spec.split('=', 1)
            if mod in mods:
                raise KeyError('Modifier {0} can only appear once'.format(mod))

            mods.add(mod)
            continue

            # TODO: Should be in something intelligent like an SPF_get
            # if mod == 'exp':
            #     res[mod] = lookup(val, 'TXT', **qargs)
            #     continue
            # elif mod == 'redirect':
            #     return query(val, 'SPF', **qargs)

        mech = {}
        if mech_spec[0] in ('+', '-', '~', '?'):
            mech['qualifier'] = mech_spec[0]
            mech_spec = mech_spec[1:]

        if ':' in mech_spec:
            mech_spec, val = mech_spec.split(':', 1)
        elif '/' in mech_spec:
            idx = mech_spec.find('/')
            mech_spec = mech_spec[0:idx]
            val = mech_spec[idx:]
        else:
            val = None

        res[mech_spec] = mech
        if not val:
            continue
        elif mech_spec in ('ip4', 'ip6'):
            val = ipaddress.ip_interface(val)
            assert val.version == int(mech_spec[-1])

        mech['value'] = val

    return res
Example #7
0
def spf_rec(rdata):
    """
    Validate and parse DNS record data for SPF record(s)
    :param rdata: DNS record data
    :return: dict w/fields
    """
    spf_fields = rdata.split(" ")
    if not spf_fields.pop(0).startswith("v=spf"):
        raise ValueError("Not an SPF record")

    res = OrderedDict()
    mods = set()
    for mech_spec in spf_fields:
        if mech_spec.startswith(("exp", "redirect")):
            # It's a modifier
            mod, val = mech_spec.split("=", 1)
            if mod in mods:
                raise KeyError("Modifier {} can only appear once".format(mod))

            mods.add(mod)
            continue

            # TODO: Should be in something intelligent like an SPF_get
            # if mod == 'exp':
            #     res[mod] = lookup(val, 'TXT', **qargs)
            #     continue
            # elif mod == 'redirect':
            #     return query(val, 'SPF', **qargs)

        mech = {}
        if mech_spec[0] in ("+", "-", "~", "?"):
            mech["qualifier"] = mech_spec[0]
            mech_spec = mech_spec[1:]

        if ":" in mech_spec:
            mech_spec, val = mech_spec.split(":", 1)
        elif "/" in mech_spec:
            idx = mech_spec.find("/")
            mech_spec = mech_spec[0:idx]
            val = mech_spec[idx:]
        else:
            val = None

        res[mech_spec] = mech
        if not val:
            continue
        elif mech_spec in ("ip4", "ip6"):
            val = ipaddress.ip_interface(val)
            assert val.version == int(mech_spec[-1])

        mech["value"] = val

    return res
Example #8
0
def _is_ipv(ip, version, options=None):

    if not version:
        version = 4

    if version not in (4, 6):
        return None

    try:
        ip_obj = ipaddress.ip_address(ip)
    except ValueError:
        # maybe it is an IP network
        try:
            ip_obj = ipaddress.ip_interface(ip)
        except ValueError:
            # nope, still not :(
            return None

    if not ip_obj.version == version:
        return None

    # has the right version, let's move on
    return _ip_options(ip_obj, version, options=options)
Example #9
0
def _is_ipv(ip, version, options=None):

    if not version:
        version = 4

    if version not in (4, 6):
        return None

    try:
        ip_obj = ipaddress.ip_address(ip)
    except ValueError:
        # maybe it is an IP network
        try:
            ip_obj = ipaddress.ip_interface(ip)
        except ValueError:
            # nope, still not :(
            return None

    if not ip_obj.version == version:
        return None

    # has the right version, let's move on
    return _ip_options(ip_obj, version, options=options)