Python netaddr.IPAddress() Examples

The following are 30 code examples of netaddr.IPAddress(). 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: format.py    From designate with Apache License 2.0 6 votes vote down vote up
def is_ipv4(instance):
    if not isinstance(instance, compat.str_types):
        return True

    try:
        address = netaddr.IPAddress(instance, version=4)
        # netaddr happly accepts, and expands "127.0" into "127.0.0.0"
        if str(address) != instance:
            return False
    except Exception:
        return False

    if instance == '0.0.0.0':  # RFC5735
        return False

    return True 
Example #2
Source File: netaddr_module.py    From Hands-On-Enterprise-Automation-with-Python with MIT License 6 votes vote down vote up
def check_ip_address(ipaddr):
    ip_attributes = []
    ipaddress = IPAddress(ipaddr)

    if ipaddress.is_private():
        ip_attributes.append("IP Address is Private")

    else:
        ip_attributes.append("IP Address is public")

    if ipaddress.is_unicast():
        ip_attributes.append("IP Address is unicast")
    elif ipaddress.is_multicast():
        ip_attributes.append("IP Address is multicast")

    if ipaddress.is_loopback():
        ip_attributes.append("IP Address is loopback")

    return "\n".join(ip_attributes) 
Example #3
Source File: vSphere.py    From im with GNU General Public License v3.0 6 votes vote down vote up
def setIps(vm, node):
        """
        Set the IPs of the VM from the info obtained from vSphere
        """
        public_ips = []
        private_ips = []

        if node.guest:
            for nic in node.guest.net:
                if nic.ipAddress:
                    ip = nic.ipAddress
                    is_private = any([IPAddress(ip) in IPNetwork(mask) for mask in Config.PRIVATE_NET_MASKS])
                    if is_private:
                        private_ips.append(ip)
                    else:
                        public_ips.append(ip)

        vm.setIps(public_ips, private_ips) 
Example #4
Source File: OpenNebula.py    From im with GNU General Public License v3.0 6 votes vote down vote up
def setIPsFromTemplate(vm, template):
        """
        Set the IPs of the VM from the info obtained in the ONE template object

        Arguments:
           - vm(:py:class:`IM.VirtualMachine`): VM information.
           - template(:py:class:`TEMPLATE`): ONE Template information.
        """
        system = vm.info.systems[0]
        for nic in template.NIC:
            i = 0
            while system.getValue("net_interface." + str(i) + ".connection"):
                net_name = system.getValue("net_interface." + str(i) + ".connection")
                net = vm.info.get_network_by_id(net_name)
                provider_id = net.getValue("provider_id")
                if provider_id == nic.NETWORK:
                    ip = str(nic.IP)
                    if IPAddress(ip).version == 6:
                        system.setValue("net_interface." + str(i) + ".ipv6", ip)
                    else:
                        system.setValue("net_interface." + str(i) + ".ip", ip)
                    break
                i += 1 
Example #5
Source File: discover_nodes.py    From JetPack with Apache License 2.0 6 votes vote down vote up
def ip_address_from_address(address):
    try:
        ip_address = netaddr.IPAddress(address)
    except ValueError as e:
        # address contains a CIDR prefix, netmask, or hostmask.
        e.message = ('invalid IP address: %(address)s (detected CIDR, netmask,'
                     ' hostmask, or subnet)') % {'address': address}
        raise
    except netaddr.AddrFormatError as e:
        # address is not an IP address represented in an accepted string
        # format.
        e.message = ("invalid IP address: '%(address)s' (failed to detect a"
                     " valid IP address)") % {'address': address}
        raise

    if ip_address.version == 4:
        return ip_address
    else:
        raise NotSupported(
            ('invalid IP address: %(address)s (Internet Protocol version'
             ' %(version)s is not supported)') % {
                'address': address,
                'version': ip_address.version}) 
Example #6
Source File: Ingestor.py    From armory with GNU General Public License v3.0 6 votes vote down vote up
def descope_ip(self, ip):
        ip = self.IPAddress.all(ip_address=ip)
        if ip:
            for i in ip:
                display("Removing IP {} from scope".format(i.ip_address))
                i.in_scope = False
                i.passive_scope = False
                i.update()
                for d in i.domains:
                    in_scope_ips = [
                        ipa
                        for ipa in d.ip_addresses
                        if ipa.in_scope or ipa.passive_scope
                    ]
                    if not in_scope_ips:
                        display(
                            "Domain {} has no more scoped IPs. Removing from scope.".format(
                                d.domain
                            )
                        )
                        d.in_scope = False
                        d.passive_scope = False
            self.IPAddress.commit() 
Example #7
Source File: data_utils.py    From tempest-lib with Apache License 2.0 6 votes vote down vote up
def get_ipv6_addr_by_EUI64(cidr, mac):
    """Generate a IPv6 addr by EUI-64 with CIDR and MAC

    :param str cidr: a IPv6 CIDR
    :param str mac: a MAC address
    :return: an IPv6 Address
    :rtype: netaddr.IPAddress
    """
    # Check if the prefix is IPv4 address
    is_ipv4 = netaddr.valid_ipv4(cidr)
    if is_ipv4:
        msg = "Unable to generate IP address by EUI64 for IPv4 prefix"
        raise TypeError(msg)
    try:
        eui64 = int(netaddr.EUI(mac).eui64())
        prefix = netaddr.IPNetwork(cidr)
        return netaddr.IPAddress(prefix.first + eui64 ^ (1 << 57))
    except (ValueError, netaddr.AddrFormatError):
        raise TypeError('Bad prefix or mac format for generating IPv6 '
                        'address by EUI-64: %(prefix)s, %(mac)s:'
                        % {'prefix': cidr, 'mac': mac})
    except TypeError:
        raise TypeError('Bad prefix type for generate IPv6 address by '
                        'EUI-64: %s' % cidr) 
Example #8
Source File: Ingestor.py    From armory with GNU General Public License v3.0 6 votes vote down vote up
def process_ip(self, ip_str, force_scope=True):

        created, ip = self.IPAddress.find_or_create(
            only_tool=True,
            ip_address=ip_str,
            in_scope=self.in_scope,
            passive_scope=self.passive_scope,
        )
        if not created:
            if ip.in_scope != self.in_scope or ip.passive_scope != self.passive_scope:
                display(
                    "IP %s already exists with different scoping. Updating to Active Scope: %s Passive Scope: %s"
                    % (ip_str, self.in_scope, self.passive_scope)
                )

                ip.in_scope = self.in_scope
                ip.passive_scope = self.passive_scope
                ip.update()
        return ip 
Example #9
Source File: ipop.py    From minemeld-core with Apache License 2.0 6 votes vote down vote up
def _range_from_indicator(self, indicator):
        if '-' in indicator:
            start, end = map(
                lambda x: int(netaddr.IPAddress(x)),
                indicator.split('-', 1)
            )
        elif '/' in indicator:
            ipnet = netaddr.IPNetwork(indicator)
            start = int(ipnet.ip)
            end = start+ipnet.size-1
        else:
            start = int(netaddr.IPAddress(indicator))
            end = start

        if (not (start >= 0 and start <= 0xFFFFFFFF)) or \
           (not (end >= 0 and end <= 0xFFFFFFFF)):
            LOG.error('%s - {%s} invalid IPv4 indicator',
                      self.name, indicator)
            return None, None

        return start, end 
Example #10
Source File: proofpoint.py    From minemeld-core with Apache License 2.0 6 votes vote down vote up
def _process_item(self, row):
        ipairs = super(EmergingThreatsIP, self)._process_item(row)

        result = []

        for i, v in ipairs:
            try:
                parsed_ip = netaddr.IPAddress(i)
            except:
                LOG.error('%s - invalid IP %s, ignored', self.name, i)
                continue

            if parsed_ip.version == 4:
                v['type'] = 'IPv4'
            elif parsed_ip.version == 6:
                v['type'] = 'IPv6'
            else:
                LOG.error('%s - unknown IP version %s, ignored', self.name, i)
                continue

            result.append([i, v])

        return result 
Example #11
Source File: base.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_dict(self):
        """
        Convert the object attributes to a dict
        :return: dict of attributes
        """
        ip = self.ip
        if type(self.ip) == list:
            ip = ["{0!s}".format(i) for i in ip]
        elif type(self.ip) == netaddr.IPAddress:
            ip = "{0!s}".format(ip)

        d = {"hostname": self.hostname,
             "ip": ip,
             "resolver_name": self.resolver_name,
             "id": self.id}
        return d 
Example #12
Source File: test_setup.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def assign_static_ip(self):
        """
        Set the static IP for the PF devices for mlx5_core driver
        """
        # This function assigns static IP for the PF devices
        pf_devices = self.get_pf_ids()
        if (not self.start_addr_PF) or (not self.net_mask):
            raise exceptions.TestSetupFail(
                "No IP / netmask found, please populate starting IP address for PF devices in configuration file")
        ip_addr = netaddr.IPAddress(self.start_addr_PF)
        for PF in pf_devices:
            ifname = utils_misc.get_interface_from_pci_id(PF)
            ip_assign = "ifconfig %s %s netmask %s up" % (
                ifname, ip_addr, self.net_mask)
            logging.info("assign IP to PF device %s : %s", PF,
                         ip_assign)
            cmd = process.system(ip_assign, shell=True, ignore_status=True)
            if cmd:
                raise exceptions.TestSetupFail("Failed to assign IP : %s"
                                               % cmd)
            ip_addr += 1
        return True 
Example #13
Source File: utils_net.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def canonicalize(self, ip_str):
        """
        Parse an IP string for listen to IPAddress content.
        """
        try:
            if ':' in ip_str:
                self.version = 'ipv6'
                if '%' in ip_str:
                    ip_str, scope = ip_str.split('%')
                    self.scope = int(scope)
                self.packed_addr = socket.inet_pton(socket.AF_INET6, ip_str)
                self.addr = socket.inet_ntop(socket.AF_INET6, self.packed_addr)
            else:
                self.version = 'ipv4'
                self.packed_addr = socket.inet_pton(socket.AF_INET, ip_str)
                self.addr = socket.inet_ntop(socket.AF_INET, self.packed_addr)
        except socket.error as detail:
            if 'illegal IP address' in str(detail):
                self.addr = ip_str
                self.version = 'hostname' 
Example #14
Source File: base.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def has_ip(self, ip):
        """
        Checks if the machine has the given IP.
        A machine might have more than one IP Address. The ip is then
        provided as a list
        :param ip: The IP address to search for
        :type ip: Netaddr IPAddress
        :return: True or false
        """
        # convert to IPAddress
        if isinstance(ip, string_types):
            ip = netaddr.IPAddress(ip)

        if type(self.ip) == list:
            return ip in self.ip
        elif type(self.ip) == netaddr.IPAddress:
            return ip == self.ip 
Example #15
Source File: machine.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_hostname(ip):
    """
    Return a hostname for a given IP address
    :param ip: IP address
    :type ip: IPAddress
    :return: hostname
    """
    machines = get_machines(ip=ip)
    if len(machines) > 1:
        raise Exception("Can not get unique ID for IP=%r. "
                        "More than one machine found." % ip)
    if len(machines) == 1:
        # There is only one machine in the list and we get its ID
        hostname = machines[0].hostname
        # return the first hostname
        if type(hostname) == list:
            hostname = hostname[0]
    else:
        raise Exception("There is no machine with IP={0!r}".format(ip))
    return hostname 
Example #16
Source File: __init__.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def check_ip_in_policy(client_ip, policy):
    """
    This checks, if the given client IP is contained in a list like

       ["10.0.0.2", "192.168.2.1/24", "!192.168.2.12", "-172.16.200.1"]

    :param client_ip: The IP address in question
    :param policy: A string of single IP addresses, negated IP address and subnets.
    :return: tuple of (found, excluded)
    """
    client_found = False
    client_excluded = False
    # Remove empty strings from the list
    policy = list(filter(None, policy))
    for ipdef in policy:
        if ipdef[0] in ['-', '!']:
            # exclude the client?
            if IPAddress(client_ip) in IPNetwork(ipdef[1:]):
                log.debug(u"the client {0!s} is excluded by {1!s}".format(client_ip, ipdef))
                client_excluded = True
        elif IPAddress(client_ip) in IPNetwork(ipdef):
            client_found = True
    return client_found, client_excluded 
Example #17
Source File: vpn_validator.py    From neutron-vpnaas with Apache License 2.0 5 votes vote down vote up
def resolve_peer_address(self, ipsec_sitecon, router):
        address = ipsec_sitecon['peer_address']
        # check if address is an ip address or fqdn
        invalid_ip_address = validators.validate_ip_address(address)
        if invalid_ip_address:
            # resolve fqdn
            try:
                addrinfo = socket.getaddrinfo(address, None)[0]
                ipsec_sitecon['peer_address'] = addrinfo[-1][0]
            except socket.gaierror:
                raise vpnaas.VPNPeerAddressNotResolved(peer_address=address)

        ip_version = netaddr.IPAddress(ipsec_sitecon['peer_address']).version
        self._validate_peer_address(ip_version, router) 
Example #18
Source File: bgp_db.py    From neutron-dynamic-routing with Apache License 2.0 5 votes vote down vote up
def _get_fip_next_hop(self, context, router_id, ip_address=None):
        router = self._get_router(context, router_id)
        gw_port = router.gw_port
        if not gw_port:
            return

        if l3_dvr_db.is_distributed_router(router) and ip_address:
            return self._get_dvr_fip_next_hop(context, ip_address)

        for fixed_ip in gw_port.fixed_ips:
            addr = netaddr.IPAddress(fixed_ip.ip_address)
            if addr.version == 4:
                return fixed_ip.ip_address 
Example #19
Source File: hosts.py    From network-tutorials with Apache License 2.0 5 votes vote down vote up
def _process_interfaces(interfaces, device_map, result):
    for interface in interfaces:
        ipv4 = []
        ipv6 = []
        for address in interface['addresses']:
            addr = netaddr.IPAddress(address.split('/')[0])
            cidr = _resolve_cidr(addr, interface['networks'])
            if addr.version == 4:
                ipv4.append(cidr)
            else:
                ipv6.append(cidr)
        interface['ipv4'] = ipv4
        interface['ipv6'] = ipv6
        result['_meta']['hostvars'][device_map[interface['device']]]['interfaces'][interface['name']] = interface  # noqa 
Example #20
Source File: hosts.py    From network-tutorials with Apache License 2.0 5 votes vote down vote up
def _process_interfaces(interfaces, device_map, result):
    for interface in interfaces:
        ipv4 = []
        ipv6 = []
        for address in interface['addresses']:
            addr = netaddr.IPAddress(address.split('/')[0])
            cidr = _resolve_cidr(addr, interface['networks'])
            if addr.version == 4:
                ipv4.append(cidr)
            else:
                ipv6.append(cidr)
        interface['ipv4'] = ipv4
        interface['ipv6'] = ipv6
        result['_meta']['hostvars'][device_map[interface['device']]]['interfaces'][interface['name']] = interface  # noqa 
Example #21
Source File: utils.py    From genielibs with Apache License 2.0 5 votes vote down vote up
def netmask_to_bits(net_mask):
    """ Convert netmask to bits
        Args:
            net_mask ('str'): Net mask IP address
            ex.) net_mask = '255.255.255.255'
        Raise:
            None
        Returns:
            Net mask bits
    """
    return IPAddress(net_mask).netmask_bits() 
Example #22
Source File: base.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, resolver_name, machine_id, hostname=None, ip=None):
        self.id = machine_id
        self.resolver_name = resolver_name
        self.hostname = hostname
        if isinstance(ip, string_types):
            self.ip = netaddr.IPAddress(ip)
        else:
            self.ip = ip 
Example #23
Source File: calico_kubernetes.py    From k8s-exec-plugin with Apache License 2.0 5 votes vote down vote up
def _read_docker_ip(self):
        """Get the IP for the pod's infra container."""
        container_info = self._get_container_info(self.docker_id)
        ip = container_info["NetworkSettings"]["IPAddress"]
        logger.info('Docker-assigned IP is %s', ip)
        return IPAddress(ip) 
Example #24
Source File: machine.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_machines(hostname=None, ip=None, id=None, resolver=None, any=None,
                 substring=True):
    """
    This returns a list of machines from ALL resolvers matching this criterion.

    :param hostname: The hostname of the machine, substring matching
    :type hostname: basestring
    :param ip: The IPAddress of the machine
    :type ip: netaddr.IPAddress
    :param id: The id of the machine, substring matching
    :type id: basestring
    :param resolver: The resolver of the machine, substring matching
    :type resolver: basestring
    :param any: a substring, that matches EITHER of hostname, ip or resolver
    :type any: basestring
    :param substring: If True, machines are search with the parameters as
        substrings
    :return: list of Machine Objects.
    """
    resolver_list = get_resolver_list()
    all_machines = []

    for reso in resolver_list.keys():
        # The resolvernames are the keys of the dictionary
        if resolver and resolver not in reso:
            # filter for other resolvers
            continue
        reso_obj = get_resolver_object(reso)
        resolver_machines = reso_obj.get_machines(hostname=hostname,
                                                  ip=ip,
                                                  machine_id=id,
                                                  any=any,
                                                  substring=substring)
        all_machines += resolver_machines

    return all_machines 
Example #25
Source File: arproxy.py    From iSDX with Apache License 2.0 5 votes vote down vote up
def start(self):
        while True:
            # receive arp requests
            packet, addr = self.sock.recvfrom(65565)
            eth_frame, arp_packet = parse_packet(packet)

            arp_type = struct.unpack("!h", arp_packet["oper"])[0]
            logger.debug("Received ARP-" + ("REQUEST" if (arp_type == 1) else "REPLY") +" SRC: "+eth_frame["src_mac"]+" / "+arp_packet["src_ip"]+" "+"DST: "+eth_frame["dst_mac"]+" / "+arp_packet["dst_ip"])

            if arp_type == 1:
                # check if the arp request stems from one of the participants
                requester_srcmac = eth_frame["src_mac"]
                requested_ip = arp_packet["dst_ip"]
                # Send the ARP request message to respective controller and forget about it
                if IPAddress(requested_ip) in config.vnhs:
                    self.send_arp_request(requester_srcmac, requested_ip)
    
                    # TODO: If the requested IP address belongs to a non-SDN participant
                    # then refer the structure `self.nonSDN_nhip_2_nhmac` and
                    # send an immediate ARP response.
                    """
                    response_vmac = self.get_vmac_default(requester_srcmac, requested_ip)
                    if response_vmac != "":
                        logger.debug("ARP-PROXY: reply with VMAC "+response_vmac)

                        data = self.craft_arp_packet(arp_packet, response_vmac)
                        eth_packet = self.craft_eth_frame(eth_frame, response_vmac, data)
                        self.sock.send(''.join(eth_packet))
                    """ 
Example #26
Source File: postpolicy.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def offline_info(request, response):
    """
    This decorator is used with the function /validate/check.
    It is not triggered by an ordinary policy but by a MachineToken definition.
    If for the given Client and Token an offline application is defined,
    the response is enhanced with the offline information - the hashes of the
    OTP.

    """
    content = response.json
    # check if the authentication was successful
    if content.get("result").get("value") is True and g.client_ip:
        # If there is no remote address, we can not determine
        # offline information
        client_ip = netaddr.IPAddress(g.client_ip)
        # check if there is a MachineToken definition
        serial = content.get("detail", {}).get("serial")
        try:
            # if the hostname can not be identified, there might be no
            # offline definition!
            hostname = get_hostname(ip=client_ip)
            auth_items = get_auth_items(hostname=hostname, ip=client_ip,
                                        serial=serial, application="offline",
                                        challenge=request.all_data.get("pass"))
            if auth_items:
                content["auth_items"] = auth_items
                response.set_data(json.dumps(content))
        except Exception as exx:
            log.info(exx)
    return response 
Example #27
Source File: fixleadingzeros.py    From designate with Apache License 2.0 5 votes vote down vote up
def fix_bad_recordsets(bad_recordsets):
    LOG.debug("Removing leading zeros in IPv4 addresses")
    for rs in bad_recordsets:
        new_records = []
        for ip in bad_recordsets[rs]['records']:
            new_records.append(
                str(netaddr.IPAddress(ip, flags=netaddr.ZEROFILL).ipv4())
            )
        bad_recordsets[rs]['records'] = new_records
    return bad_recordsets 
Example #28
Source File: format.py    From designate with Apache License 2.0 5 votes vote down vote up
def is_ipv6(instance):
    if not isinstance(instance, compat.str_types):
        return True

    try:
        netaddr.IPAddress(instance, version=6)
    except Exception:
        return False

    return True 
Example #29
Source File: Ingestor.py    From armory with GNU General Public License v3.0 5 votes vote down vote up
def descope_cidr(self, cidr):
        CIDR = self.ScopeCIDR.all(cidr=cidr)
        if CIDR:
            for c in CIDR:
                display("Removing {} from ScopeCIDRs".format(c.cidr))
                c.delete()
        cnet = IPNetwork(cidr)
        for ip in self.IPAddress.all():
            if IPAddress(ip.ip_address) in cnet:

                self.descope_ip(ip.ip_address) 
Example #30
Source File: kube_plugin_test.py    From k8s-exec-plugin with Apache License 2.0 5 votes vote down vote up
def test_status(self, m_print):
        """Test Pod Status Hook"""
        # Set up args
        namespace = 'ns'
        pod_name = 'pod1'
        docker_id = 123456789101112

        # Call method under test
        endpoint = Endpoint(TEST_HOST, TEST_ORCH_ID, '1234', '5678',
                            'active', 'mac')
        ipv4 = IPAddress('1.1.1.1')
        ipv4_2 = IPAddress('1.1.1.2')
        ipv6 = IPAddress('201:db8::')
        endpoint.ipv4_nets.add(IPNetwork(ipv4))
        endpoint.ipv4_nets.add(IPNetwork(ipv4_2))
        endpoint.ipv6_nets.add(IPNetwork(ipv6))
        self.m_datastore_client.get_endpoint.return_value = endpoint

        json_dict = {
            "apiVersion": "v1beta1",
            "kind": "PodNetworkStatus",
            "ip": "1.1.1.2"
        }

        self.plugin.status(namespace, pod_name, docker_id)
        self.m_datastore_client.get_endpoint.assert_called_once_with(hostname=TEST_HOST,
                                                                     orchestrator_id=TEST_ORCH_ID,
                                                                     workload_id=docker_id)
        m_print.assert_called_once_with(json.dumps(json_dict))