Python netaddr.valid_ipv6() Examples

The following are 28 code examples of netaddr.valid_ipv6(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module netaddr , or try the search function .
Example #1
Source File: http_ping.py    From tacker with Apache License 2.0 6 votes vote down vote up
def _is_pingable(self, mgmt_ip='', retry=5, timeout=5, port=80, **kwargs):
        """Checks whether the server is reachable by using urllib.

        Waits for connectivity for `timeout` seconds,
        and if connection refused, it will retry `retry`
        times.
        :param mgmt_ip: IP to check
        :param retry: times to reconnect if connection refused
        :param timeout: seconds to wait for connection
        :param port: port number to check connectivity
        :return: bool - True or False depending on pingability.
        """
        url = 'http://' + mgmt_ip + ':' + str(port)
        if netaddr.valid_ipv6(mgmt_ip):
            url = 'http://[' + mgmt_ip + ']:' + str(port)

        for retry_index in range(int(retry)):
            try:
                urlreq.urlopen(url, timeout=timeout)
                return True
            except urlerr.URLError:
                LOG.warning('Unable to reach to the url %s', url)
        return 'failure' 
Example #2
Source File: netutils.py    From oslo.utils with Apache License 2.0 6 votes vote down vote up
def is_valid_ipv6(address):
    """Verify that address represents a valid IPv6 address.

    :param address: Value to verify
    :type address: string
    :returns: bool

    .. versionadded:: 1.1
    """
    if not address:
        return False

    parts = address.rsplit("%", 1)
    address = parts[0]
    scope = parts[1] if len(parts) > 1 else None
    if scope is not None and (len(scope) < 1 or len(scope) > 15):
        return False

    try:
        return netaddr.valid_ipv6(address, netaddr.core.INET_PTON)
    except netaddr.AddrFormatError:
        return False 
Example #3
Source File: zabbix.py    From tacker with Apache License 2.0 6 votes vote down vote up
def get_token_from_zbxserver(self, node):

        temp_auth_api = copy.deepcopy(zapi.dAUTH_API)
        temp_auth_api['params']['user'] = \
            self.hostinfo[node]['zbx_info']['zabbix_user']
        temp_auth_api['params']['password'] = \
            self.hostinfo[node]['zbx_info']['zabbix_pass']
        zabbixip = \
            self.hostinfo[node]['zbx_info']['zabbix_ip']
        zabbixport = \
            self.hostinfo[node]['zbx_info']['zabbix_port']
        self.URL = "http://" + zabbixip + ":" + \
                   str(zabbixport) + zapi.URL
        if netaddr.valid_ipv6(zabbixip):
            self.URL = "http://[" + zabbixip + "]:" + \
                       str(zabbixport) + zapi.URL
        response = requests.post(
            self.URL,
            headers=zapi.HEADERS,
            data=jsonutils.dump_as_bytes(temp_auth_api)
        )
        response_dict = dict(response.json())
        VNFMonitorZabbix.check_error(response_dict)
        LOG.info('Success Connect Zabbix Server')
        return response_dict['result'] 
Example #4
Source File: ceilometer.py    From tacker with Apache License 2.0 6 votes vote down vote up
def _create_alarm_url(self, vnf_id, mon_policy_name, mon_policy_action):
        # alarm_url = 'http://host:port/v1.0/vnfs/vnf-uuid/monitoring-policy
        # -name/action-name?key=8785'
        host = cfg.CONF.ceilometer.host
        port = cfg.CONF.ceilometer.port
        LOG.info("Tacker in heat listening on %(host)s:%(port)s",
                 {'host': host,
                  'port': port})
        origin = "http://%(host)s:%(port)s/v1.0/vnfs" % {
            'host': host, 'port': port}
        if netaddr.valid_ipv6(host):
            origin = "http://[%(host)s]:%(port)s/v1.0/vnfs" % {
                'host': host, 'port': port}
        access_key = ''.join(
            random.SystemRandom().choice(
                string.ascii_lowercase + string.digits)
            for _ in range(8))
        alarm_url = "".join([origin, '/', vnf_id, '/', mon_policy_name, '/',
                             mon_policy_action, '/', access_key])
        return alarm_url 
Example #5
Source File: vim_ping_action.py    From tacker with Apache License 2.0 6 votes vote down vote up
def _ping(self):

        cmd_ping = 'ping'
        if netaddr.valid_ipv6(self.targetip):
            cmd_ping = 'ping6'

        ping_cmd = [cmd_ping, '-c', self.count,
                    '-W', self.timeout,
                    '-i', self.interval,
                    self.targetip]

        try:
            # NOTE(gongysh) since it is called in a loop, the debug log
            # should be disabled to avoid eating up mistral executor.
            linux_utils.execute(ping_cmd, check_exit_code=True,
                                debuglog=False)
            return 'REACHABLE'
        except RuntimeError:
            LOG.warning(("Cannot ping ip address: %s"), self.targetip)
            return 'UNREACHABLE' 
Example #6
Source File: networkconfig.py    From cloudbase-init with Apache License 2.0 5 votes vote down vote up
def _process_networks(osutils, network_details):
        reboot_required = False
        ipv4_ns, ipv6_ns = NetworkConfigPlugin._get_default_dns_nameservers(
            network_details)

        for net in network_details.networks:
            ip_address, prefix_len = net.address_cidr.split("/")

            gateway = None
            default_gw_route = [
                r for r in net.routes if
                netaddr.IPNetwork(r.network_cidr).prefixlen == 0]
            if default_gw_route:
                gateway = default_gw_route[0].gateway

            nameservers = net.dns_nameservers
            if not nameservers:
                if netaddr.valid_ipv6(ip_address):
                    nameservers = ipv6_ns
                else:
                    nameservers = ipv4_ns

            LOG.info(
                "Setting static IP configuration on network adapter "
                "\"%(name)s\". IP: %(ip)s, prefix length: %(prefix_len)s, "
                "gateway: %(gateway)s, dns: %(dns)s",
                {"name": net.link, "ip": ip_address, "prefix_len": prefix_len,
                 "gateway": gateway, "dns": nameservers})
            reboot = osutils.set_static_network_config(
                net.link, ip_address, prefix_len, gateway, nameservers)
            reboot_required = reboot or reboot_required

        return reboot_required 
Example #7
Source File: utils.py    From neutron-dynamic-routing with Apache License 2.0 5 votes vote down vote up
def validate_ip_addr(ip_addr):
    if netaddr.valid_ipv4(ip_addr):
        return lib_consts.IP_VERSION_4
    elif netaddr.valid_ipv6(ip_addr):
        return lib_consts.IP_VERSION_6
    else:
        raise bgp_driver_exc.InvalidParamType(param=ip_addr,
                                              param_type='ip-address') 
Example #8
Source File: __init__.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_valid_ip(ip):
    """Check the validity of an IP address."""
    return valid_ipv4(ip) or valid_ipv6(ip) 
Example #9
Source File: __init__.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def contains_managed_ipv6_interface(interfaces):
    """Does any of a list of cluster interfaces manage a IPv6 subnet?"""
    return any(
        interface.manages_static_range() and valid_ipv6(interface.ip)
        for interface in interfaces
    ) 
Example #10
Source File: service.py    From oslo.vmware with Apache License 2.0 5 votes vote down vote up
def build_base_url(protocol, host, port):
        proto_str = '%s://' % protocol
        host_str = '[%s]' % host if netaddr.valid_ipv6(host) else host
        port_str = '' if port is None else ':%d' % port
        return proto_str + host_str + port_str 
Example #11
Source File: createIPBlockList.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def isIPv6(ip):
    try:
        return netaddr.valid_ipv6(ip)
    except:
        return False 
Example #12
Source File: ipaddr.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def isIPv6(ip):
    try:
        return netaddr.valid_ipv6(ip)
    except:
        return False 
Example #13
Source File: ipblocklist.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def isIPv6(ip):
    try:
        return netaddr.valid_ipv6(ip)
    except:
        return False 
Example #14
Source File: broFixup.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def isIPv6(ip):
    try:
        return netaddr.valid_ipv6(ip)
    except:
        return False 
Example #15
Source File: ipFixup.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def isIPv6(ip):
    try:
        return netaddr.valid_ipv6(ip)
    except:
        return False 
Example #16
Source File: _utils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def parse_server_string(server_str):
    """Parses the given server_string and returns a tuple of host and port.

    If it's not a combination of host part and port, the port element
    is an empty string. If the input is invalid expression, return a tuple of
    two empty strings.
    """

    try:
        # First of all, exclude pure IPv6 address (w/o port).
        if netaddr.valid_ipv6(server_str):
            return (server_str, '')

        # Next, check if this is IPv6 address with a port number combination.
        if server_str.find("]:") != -1:
            (address, port) = server_str.replace('[', '', 1).split(']:')
            return (address, port)

        # Third, check if this is a combination of an address and a port
        if server_str.find(':') == -1:
            return (server_str, '')

        # This must be a combination of an address and a port
        (address, port) = server_str.split(':')
        return (address, port)

    except (ValueError, netaddr.AddrFormatError):
        LOG.error('Invalid server_string: %s', server_str)
        return ('', '') 
Example #17
Source File: loginsight.py    From osprofiler with Apache License 2.0 5 votes vote down vote up
def _build_base_url(self, scheme):
        proto_str = "%s://" % scheme
        host_str = ("[%s]" % self._host if netaddr.valid_ipv6(self._host)
                    else self._host)
        port_str = ":%d" % (self._api_ssl_port if scheme == "https"
                            else self._api_port)
        return proto_str + host_str + port_str 
Example #18
Source File: helpers.py    From Loki with GNU General Public License v3.0 5 votes vote down vote up
def is_ip(string):
    try:
        if netaddr.valid_ipv4(string):
            return True
        if netaddr.valid_ipv6(string):
            return True
        return False
    except:
        traceback.print_exc()
        return False 
Example #19
Source File: ping.py    From tacker with Apache License 2.0 5 votes vote down vote up
def _is_pingable(self, mgmt_ip="", count=None, timeout=None,
                     interval=None, retry=None, **kwargs):
        """Checks whether an IP address is reachable by pinging.

        Use linux utils to execute the ping (ICMP ECHO) command.
        Sends 5 packets with an interval of 1 seconds and timeout of 1
        seconds. Runtime error implies unreachability else IP is pingable.
        :param ip: IP to check
        :return: bool - True or string 'failure' depending on pingability.
        """
        cmd_ping = 'ping'
        if netaddr.valid_ipv6(mgmt_ip):
            cmd_ping = 'ping6'

        if not count:
            count = cfg.CONF.monitor_ping.count
        if not timeout:
            timeout = cfg.CONF.monitor_ping.timeout
        if not interval:
            interval = cfg.CONF.monitor_ping.interval
        if not retry:
            retry = cfg.CONF.monitor_ping.retry

        ping_cmd = [cmd_ping,
                    '-c', count,
                    '-W', timeout,
                    '-i', interval,
                    mgmt_ip]

        for retry_range in range(int(retry)):
            try:
                linux_utils.execute(ping_cmd, check_exit_code=True)
                return True
            except RuntimeError:
                LOG.warning("Cannot ping ip address: %s", mgmt_ip)
        return 'failure' 
Example #20
Source File: windows.py    From cloudbase-init with Apache License 2.0 5 votes vote down vote up
def _set_static_network_config_legacy(name, address, netmask, gateway,
                                          dnsnameservers):
        if netaddr.valid_ipv6(address):
            LOG.warning("Setting IPv6 info not available on this system")
            return

        adapter_config = WindowsUtils._get_network_adapter(name).associators(
            wmi_result_class='Win32_NetworkAdapterConfiguration')[0]

        LOG.debug("Setting static IP address")
        (ret_val,) = adapter_config.EnableStatic([address], [netmask])
        if ret_val > 1:
            raise exception.CloudbaseInitException(
                "Cannot set static IP address on network adapter: %d" %
                ret_val)
        reboot_required = (ret_val == 1)

        if gateway:
            LOG.debug("Setting static gateways")
            (ret_val,) = adapter_config.SetGateways([gateway], [1])
            if ret_val > 1:
                raise exception.CloudbaseInitException(
                    "Cannot set gateway on network adapter: %d" % ret_val)
            reboot_required = reboot_required or ret_val == 1

        if dnsnameservers:
            LOG.debug("Setting static DNS servers")
            (ret_val,) = adapter_config.SetDNSServerSearchOrder(dnsnameservers)
            if ret_val > 1:
                raise exception.CloudbaseInitException(
                    "Cannot set DNS on network adapter: %d" % ret_val)
            reboot_required = reboot_required or ret_val == 1

        return reboot_required 
Example #21
Source File: windows.py    From cloudbase-init with Apache License 2.0 5 votes vote down vote up
def _set_static_network_config(name, address, prefix_len, gateway):
        if netaddr.valid_ipv6(address):
            family = AF_INET6
        else:
            family = AF_INET

        # This is needed to avoid the error:
        # "Inconsistent parameters PolicyStore PersistentStore and
        # Dhcp Enabled"
        WindowsUtils._fix_network_adapter_dhcp(name, False, family)

        conn = wmi.WMI(moniker='//./root/standardcimv2')
        existing_addresses = conn.MSFT_NetIPAddress(
            AddressFamily=family, InterfaceAlias=name)
        for existing_address in existing_addresses:
            LOG.debug(
                "Removing existing IP address \"%(ip)s\" "
                "from adapter \"%(name)s\"",
                {"ip": existing_address.IPAddress, "name": name})
            existing_address.Delete_()

        existing_routes = conn.MSFT_NetRoute(
            AddressFamily=family, InterfaceAlias=name)
        for existing_route in existing_routes:
            LOG.debug(
                "Removing existing route \"%(route)s\" "
                "from adapter \"%(name)s\"",
                {"route": existing_route.DestinationPrefix, "name": name})
            existing_route.Delete_()

        conn.MSFT_NetIPAddress.create(
            AddressFamily=family, InterfaceAlias=name, IPAddress=address,
            PrefixLength=prefix_len, DefaultGateway=gateway) 
Example #22
Source File: utils.py    From python-tripleoclient with Apache License 2.0 5 votes vote down vote up
def is_valid_ip(ip):
    """Return True if the IP is either v4 or v6

    Return False if invalid.
    """
    return netaddr.valid_ipv4(ip) or netaddr.valid_ipv6(ip) 
Example #23
Source File: bgpspeaker.py    From ryu with Apache License 2.0 5 votes vote down vote up
def _check_rf_and_normalize(prefix):
        """ check prefix's route_family and if the address is
        IPv6 address, return IPv6 route_family and normalized IPv6 address.
        If the address is IPv4 address, return IPv4 route_family
        and the prefix itself.

        """
        ip, masklen = prefix.split('/')
        if netaddr.valid_ipv6(ip):
            # normalize IPv6 address
            ipv6_prefix = str(netaddr.IPAddress(ip)) + '/' + masklen
            return vrfs.VRF_RF_IPV6, ipv6_prefix
        else:
            return vrfs.VRF_RF_IPV4, prefix 
Example #24
Source File: neighbors.py    From ryu with Apache License 2.0 5 votes vote down vote up
def valid_ip_address(addr):
    if not netaddr.valid_ipv4(addr) and not netaddr.valid_ipv6(addr):
        return False
    return True 
Example #25
Source File: networkconfig.py    From cloudbase-init with Apache License 2.0 5 votes vote down vote up
def _get_default_dns_nameservers(network_details):
        ipv4_nameservers = []
        ipv6_nameservers = []
        for s in network_details.services:
            if isinstance(s, network_model.NameServerService):
                for nameserver in s.addresses:
                    if netaddr.valid_ipv6(nameserver):
                        ipv6_nameservers.append(nameserver)
                    else:
                        ipv4_nameservers.append(nameserver)
        return (ipv4_nameservers, ipv6_nameservers) 
Example #26
Source File: select.py    From DeepSea with GNU General Public License v3.0 4 votes vote down vote up
def public_addresses(tuples=False, host=False, roles=None, roles_or=None, url=False, **kwargs):
    """
    Returns an array of public addresses matching the search critieria.
    Can also return an array of tuples with fqdn or short name.
    """
    criteria = []
    for key in kwargs:
        if key[0] == "_":
            continue
        criteria.append("I@{}:{}".format(key, kwargs[key]))

    if roles_or is not None:
        if not isinstance(roles_or, list):
            roles_or = [roles_or]
        roles_target = ["I@roles:{}".format(role) for role in roles_or]
        criteria.append("( {} )".format(" or ".join(roles_target)))

    if roles is not None:
        if not isinstance(roles, list):
            roles = [roles]
            criteria.extend(["I@roles:{}".format(role) for role in roles])

    search = " and ".join(criteria)

    # When search matches no minions, salt prints to stdout.  Suppress stdout.
    _stdout = sys.stdout
    sys.stdout = open(os.devnull, 'w')

    local = salt.client.LocalClient()
    result = local.cmd(search, 'public.address', [], tgt_type="compound")

    sys.stdout = _stdout

    def format_addr(addr):
        """
        Format IP address when used for URLs
        """
        if url:
            if netaddr.valid_ipv6(addr) is True:
                return "[{}]".format(addr)
        return addr

    if tuples:
        if host:
            addresses = [[_grain_host(local, k), format_addr(v)] for k, v in result.items()]
        else:
            addresses = [[k, format_addr(v)] for k, v in result.items()]
    else:
        addresses = []
        for entry in result:
            addresses.append(format_addr(result[entry]))

    return addresses 
Example #27
Source File: gluster.py    From avocado-vt with GNU General Public License v2.0 4 votes vote down vote up
def create_gluster_uri(params, stripped=False):
    """
    Create gluster volume uri when using TCP:
      stripped: gluster_server:/volume
      not stripped: gluster[+transport]://gluster_server[:port]/volume
    Create gluster image uri when using unix socket:
      gluster+unix:///volume/path?socket=/path/to/socket
    """
    vol_name = params.get("gluster_volume_name")

    # Access gluster server by unix domain socket
    is_unix_socket = os.path.exists(params.get("gluster_unix_socket", ""))

    error_context.context("Host name lookup failed")
    gluster_server = params.get("gluster_server")
    if not gluster_server or is_unix_socket:
        gluster_server = socket.gethostname()
    if not gluster_server or gluster_server == "(none)":
        gluster_server = utils_net.get_host_ip_address(params)

    # Start the gluster dameon, if not started
    # Building gluster uri
    gluster_uri = None
    if stripped:
        gluster_uri = "%s:/%s" % (gluster_server, vol_name)
    else:
        volume = "/%s/" % vol_name

        if is_unix_socket:
            sock = "?socket=%s" % params["gluster_unix_socket"]
            img = params.get("image_name").split('/')[-1]
            fmt = params.get("image_format", "qcow2")
            image_path = img if params.get_boolean(
                "image_raw_device") else "%s.%s" % (img, fmt)
            gluster_uri = "gluster+unix://{v}{p}{s}".format(v=volume,
                                                            p=image_path,
                                                            s=sock)
        else:
            # Access gluster server by hostname or ip
            gluster_transport = params.get("gluster_transport")
            transport = "+%s" % gluster_transport if gluster_transport else ""

            # QEMU will send 0 which will make gluster to use the default port
            gluster_port = params.get("gluster_port")
            port = ":%s" % gluster_port if gluster_port else ""

            # [IPv6 address]
            server = "[%s]" % gluster_server if netaddr.valid_ipv6(
                                gluster_server) else gluster_server

            host = "%s%s" % (server, port)

            gluster_uri = "gluster{t}://{h}{v}".format(t=transport,
                                                       h=host,
                                                       v=volume)

    return gluster_uri 
Example #28
Source File: nocloudservice.py    From cloudbase-init with Apache License 2.0 4 votes vote down vote up
def _parse_subnets(self, subnets, link_name):
        networks = []

        if not subnets or not isinstance(subnets, list):
            LOG.warning("Subnets '%s' is empty or not a list.",
                        subnets)
            return networks

        for subnet in subnets:
            if not isinstance(subnet, dict):
                LOG.warning("Subnet '%s' is not a dictionary",
                            subnet)
                continue

            if subnet.get("type") in ["dhcp", "dhcp6"]:
                continue

            routes = []
            for route_data in subnet.get("routes", []):
                route_netmask = route_data.get("netmask")
                route_network = route_data.get("network")
                route_network_cidr = network_utils.ip_netmask_to_cidr(
                    route_network, route_netmask)

                route_gateway = route_data.get("gateway")
                route = network_model.Route(
                    network_cidr=route_network_cidr,
                    gateway=route_gateway
                )
                routes.append(route)

            address_cidr = subnet.get("address")
            netmask = subnet.get("netmask")
            if netmask:
                address_cidr = network_utils.ip_netmask_to_cidr(
                    address_cidr, netmask)

            gateway = subnet.get("gateway")
            if gateway:
                # Map the gateway as a default route, depending on the
                # IP family / version (4 or 6)
                gateway_net_cidr = "0.0.0.0/0"
                if netaddr.valid_ipv6(gateway):
                    gateway_net_cidr = "::/0"

                routes.append(
                    network_model.Route(
                        network_cidr=gateway_net_cidr,
                        gateway=gateway
                    )
                )

            networks.append(network_model.Network(
                link=link_name,
                address_cidr=address_cidr,
                dns_nameservers=subnet.get("dns_nameservers"),
                routes=routes
            ))

        return networks