Python netaddr.IPNetwork() Examples

The following are 30 code examples for showing how to use netaddr.IPNetwork(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module netaddr , or try the search function .

Example 1
Project: cloudfrunt   Author: MindPointGroup   File: cloudfrunt.py    License: MIT License 6 votes vote down vote up
def get_cf_domain(domain,cf_ranges):

    if domain.endswith('cloudfront.net'):
        return False

    domain_ips = []

    try:
        domain_ips = socket.gethostbyname_ex(domain)[2]
    except:
        pass

    for ip in domain_ips:
        for ip_range in cf_ranges:
            ip_network = IPNetwork(ip_range)
            if ip in ip_network:
                print(' [+] Found CloudFront domain --> ' + str(domain))
                return True
    return False

# test domains for CloudFront misconfigurations 
Example 2
Project: JetPack   Author: dsp-jetpack   File: discover_nodes.py    License: Apache License 2.0 6 votes vote down vote up
def ip_network_from_address(address):
    try:
        ip_network = netaddr.IPNetwork(address)
    except netaddr.AddrFormatError as e:
        # address is not an IP address represented in an accepted string
        # format.
        e.message = ("invalid IP network: '%(address)s' (failed to detect a"
                     " valid IP network)") % {
            'address': address}
        raise

    if ip_network.version == 4:
        return ip_network
    else:
        raise NotSupported(
            ('invalid IP network: %(address)s (Internet Protocol version'
             ' %(version)s is not supported)') % {
                'address': address,
                'version': ip_network.version}) 
Example 3
Project: JetPack   Author: dsp-jetpack   File: config_dashboard.py    License: Apache License 2.0 6 votes vote down vote up
def initialize(self):
        self.fqdn = self.run("hostname")
        self._read_machine_id()

        # Find the node's IP address on the storage network
        addrs = self.run("sudo ip -4 addr | awk '$1 == \"inet\" {print $2}'")
        for addr in addrs.split("\n"):
            ip_network = IPNetwork(addr)
            if ip_network == Node.storage_network:
                self.storage_ip = str(ip_network.ip)
                break

        if not getattr(self, "storage_ip", None):
            msg = "Node at {} does not have an IP address on the storage" \
                  " network".format(self.address)
            LOG.error(msg)
            raise DashboardException(msg) 
Example 4
Project: ec2-api   Author: openstack   File: validator.py    License: Apache License 2.0 6 votes vote down vote up
def _is_valid_cidr(address):
    """Check if address is valid

    The provided address can be a IPv6 or a IPv4
    CIDR address.
    """
    try:
        # Validate the correct CIDR Address
        netaddr.IPNetwork(address)
    except netaddr.core.AddrFormatError:
        return False
    except UnboundLocalError:
        # NOTE(MotoKen): work around bug in netaddr 0.7.5 (see detail in
        # https://github.com/drkjam/netaddr/issues/2)
        return False

    # Prior validation partially verify /xx part
    # Verify it here
    ip_segment = address.split('/')

    if (len(ip_segment) <= 1 or
            ip_segment[1] == ''):
        return False

    return True 
Example 5
Project: im   Author: grycap   File: vSphere.py    License: 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 6
Project: im   Author: grycap   File: CloudConnector.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_nets_common_cird(radl):
        """
        Get a common CIDR in all the RADL nets
        """
        nets = []
        for num, net in enumerate(radl.networks):
            provider_id = net.getValue('provider_id')
            if net.getValue('create') == 'yes' and not net.isPublic() and not provider_id:
                net_cidr = net.getValue('cidr')
                if not net_cidr:
                    net_cidr = CloudConnector.DEFAULT_NET_CIDR
                net_cidr_0 = IPNetwork(net_cidr.replace("*", "0"))
                if net_cidr_0 not in nets:
                    nets.append(net_cidr_0)
                net_cidr = IPNetwork(net_cidr.replace("*", str(num + 1)))
                nets.append(net_cidr)

        if len(nets) == 0:  # there is no CIDR return the default one
            return "10.0.0.0/16"
        elif len(nets) == 1:  # there is only one, return it
            return nets[0]
        else:  # there are more, get the common CIDR
            return str(spanning_cidr(nets)) 
Example 7
Project: tempest-lib   Author: openstack   File: data_utils.py    License: 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
Project: os-net-config   Author: openstack   File: impl_eni.py    License: Apache License 2.0 6 votes vote down vote up
def _add_routes(self, interface_name, routes=[]):
        logger.info('adding custom route for interface: %s' % interface_name)
        data = ""
        for route in routes:
            options = ""
            if route.route_options:
                options = " %s" % (route.route_options)
            if route.default and not route.ip_netmask:
                rt = netaddr.IPNetwork("0.0.0.0/0")
            else:
                rt = netaddr.IPNetwork(route.ip_netmask)
            data += "up route add -net %s netmask %s gw %s%s\n" % (
                    str(rt.ip), str(rt.netmask), route.next_hop, options)
            data += "down route del -net %s netmask %s gw %s%s\n" % (
                    str(rt.ip), str(rt.netmask), route.next_hop, options)
        self.routes[interface_name] = data
        logger.debug('route data: %s' % self.routes[interface_name]) 
Example 9
Project: ScoutSuite   Author: nccgroup   File: base.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_cidr_name(cidr, ip_ranges_files, ip_ranges_name_key):
    """Read display name for CIDRs from ip-ranges files."""

    for filename in ip_ranges_files:
        ip_ranges = read_ip_ranges(filename, local_file=True)
        for ip_range in ip_ranges:
            ip_prefix = netaddr.IPNetwork(ip_range['ip_prefix'])
            cidr = netaddr.IPNetwork(cidr)
            if cidr in ip_prefix:
                return ip_range[ip_ranges_name_key].strip()
    for ip_range in aws_ip_ranges:
        ip_prefix = netaddr.IPNetwork(ip_range['ip_prefix'])
        cidr = netaddr.IPNetwork(cidr)
        if cidr in ip_prefix:
            return 'Unknown CIDR in %s %s' % (ip_range['service'], ip_range['region'])
    return 'Unknown CIDR' 
Example 10
Project: minemeld-core   Author: PaloAltoNetworks   File: google.py    License: Apache License 2.0 6 votes vote down vote up
def _build_IPv4(self, netblock, ipnetwork):
        try:
            n = netaddr.IPNetwork(ipnetwork)
            if n.version != 4:
                raise ValueError('invalid ip4 network: %d' % n.version)
        except:
            LOG.exception('%s - Invalid ip4 network: %s', self.name, ipnetwork)
            return {}

        item = {
            'indicator': ipnetwork,
            'type': 'IPv4',
            'confidence': 100,
            self.BLOCK_ATTRIBUTE: netblock,
            'sources': [self.SOURCE_NAME]
        }
        return item 
Example 11
Project: minemeld-core   Author: PaloAltoNetworks   File: google.py    License: Apache License 2.0 6 votes vote down vote up
def _build_IPv6(self, netblock, ipnetwork):
        try:
            n = netaddr.IPNetwork(ipnetwork)
            if n.version != 6:
                raise ValueError('invalid ip6 network: %d' % n.version)
        except:
            LOG.exception('%s - Invalid ip6 network: %s', self.name, ipnetwork)
            return {}

        item = {
            'indicator': ipnetwork,
            'type': 'IPv6',
            'confidence': 100,
            self.BLOCK_ATTRIBUTE: netblock,
            'sources': [self.SOURCE_NAME]
        }
        return item 
Example 12
Project: minemeld-core   Author: PaloAltoNetworks   File: ipop.py    License: 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 13
Project: minemeld-core   Author: PaloAltoNetworks   File: azure.py    License: Apache License 2.0 6 votes vote down vote up
def _build_IP(nodename, address_prefix, **keywords):
    try:
        ap = netaddr.IPNetwork(address_prefix)
    except Exception:
        LOG.exception('%s - Invalid ip range: %s', nodename, address_prefix)
        return {}

    if ap.version == 4:
        type_ = 'IPv4'
    elif ap.version == 6:
        type_ = 'IPv6'
    else:
        LOG.error('{} - Unknown IP version: {}'.format(nodename, ap.version))
        return {}

    item = {
        'indicator': address_prefix,
        'type': type_,
        'confidence': 100,
        'sources': [nodename]
    }
    item.update(keywords)

    return item 
Example 14
Project: px   Author: genotrance   File: px.py    License: MIT License 6 votes vote down vote up
def parse_ip_ranges(iprangesconfig):
    ipranges = netaddr.IPSet([])

    iprangessplit = [i.strip() for i in iprangesconfig.split(",")]
    for iprange in iprangessplit:
        if not iprange:
            continue

        try:
            if "-" in iprange:
                spl = iprange.split("-", 1)
                ipns = netaddr.IPRange(spl[0], spl[1])
            elif "*" in iprange:
                ipns = netaddr.IPGlob(iprange)
            else:
                ipns = netaddr.IPNetwork(iprange)
            ipranges.add(ipns)
        except:
            pprint("Bad IP definition: %s" % iprangesconfig)
            sys.exit()
    return ipranges 
Example 15
Project: avocado-vt   Author: avocado-framework   File: utils_net.py    License: GNU General Public License v2.0 6 votes vote down vote up
def gen_ipv4_addr(network_num="10.0.0.0", network_prefix="24", exclude_ips=[]):
    """
    generate ipv4 address
    :param network_num: network number to be used
    :param network_prefix: prefix used to get subnet mask to calculate ip range
    :param exclude_ips: the list of ipaddress should be excluded

    :return: ipaddress of type str
    """
    ip_regex = "^\d+.\d+.\d+.\d+$"
    exclude_ips = set(exclude_ips)
    if not re.match(ip_regex, network_num):
        network_num = "10.0.0.0"
    if not exclude_ips and network_prefix == "24":
        exclude_ips.add(network_num)
        exclude_ips.add('.'.join(network_num.split('.')[0:3]) + ".%s" %
                        str(1))
        exclude_ips.add(('.'.join(network_num.split('.')[0:3]) + ".%s" %
                         str(255)))
    network = netaddr.IPNetwork("%s/%s" % (network_num, network_prefix))
    for ip_address in network:
        if str(ip_address) not in exclude_ips:
            yield str(ip_address) 
Example 16
Project: privacyidea   Author: privacyidea   File: __init__.py    License: 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
Project: neutron-vpnaas   Author: openstack   File: ipsec.py    License: Apache License 2.0 6 votes vote down vote up
def _virtual_privates(self, vpnservice):
        """Returns line of virtual_privates.

        virtual_private contains the networks
        that are allowed as subnet for the remote client.
        """
        virtual_privates = []
        nets = []
        for ipsec_site_conn in vpnservice['ipsec_site_connections']:
            nets += ipsec_site_conn['local_cidrs']
            nets += ipsec_site_conn['peer_cidrs']
        for net in nets:
            version = netaddr.IPNetwork(net).version
            virtual_privates.append('%%v%s:%s' % (version, net))
        virtual_privates.sort()
        return ','.join(virtual_privates) 
Example 18
Project: neutron-vpnaas   Author: openstack   File: ipsec.py    License: Apache License 2.0 6 votes vote down vote up
def _update_nat(self, vpnservice, func):
        """Setting up nat rule in iptables.

        We need to setup nat rule for ipsec packet.
        :param vpnservice: vpnservices
        :param func: self.add_nat_rule or self.remove_nat_rule
        """
        router_id = vpnservice['router_id']
        for ipsec_site_connection in vpnservice['ipsec_site_connections']:
            for local_cidr in ipsec_site_connection['local_cidrs']:
                # This ipsec rule is not needed for ipv6.
                if netaddr.IPNetwork(local_cidr).version == 6:
                    continue

                for peer_cidr in ipsec_site_connection['peer_cidrs']:
                    func(router_id,
                         'POSTROUTING',
                         '-s %s -d %s -m policy '
                         '--dir out --pol ipsec '
                         '-j ACCEPT ' % (local_cidr, peer_cidr),
                         top=True)
        self.iptables_apply(router_id) 
Example 19
Project: iSDX   Author: sdn-ixp   File: arproxy.py    License: Apache License 2.0 5 votes vote down vote up
def parse_config(config_file):
    "Parse the config file"

    with open(config_file, 'r') as f:
        config = json.load(f)

    vnhs = IPNetwork(config["VNHs"])

    host, port = config["ARP Proxy"]["GARP_SOCKET"]
    garp_socket = (host, int(port))

    interface = config["ARP Proxy"]["Interface"]

    return Config(vnhs, garp_socket, interface) 
Example 20
Project: iSDX   Author: sdn-ixp   File: lib.py    License: Apache License 2.0 5 votes vote down vote up
def parse_various(self):
        config = self.config

        participant = config["Participants"][self.id]

        self.ports = participant["Ports"]
        self.port0_mac = self.ports[0]["MAC"]

        self.peers_in = participant["Peers"]
        self.peers_out = self.peers_in

        self.asn = participant["ASN"]


        self.VNHs = IPNetwork(config["VNHs"]) 
Example 21
Project: JetPack   Author: dsp-jetpack   File: network_helper.py    License: Apache License 2.0 5 votes vote down vote up
def get_provisioning_network():
        pattern = re.compile("^cidr\s*=\s*(.+)$")  # noqa: W605
        undercloud_conf = open(os.path.join(os.path.expanduser('~'), 'pilot',
                                            'undercloud.conf'), 'r')

        cidr = None
        for line in undercloud_conf:
            match = pattern.match(line)
            if match:
                cidr = netaddr.IPNetwork(match.group(1))
                break

        return cidr 
Example 22
Project: JetPack   Author: dsp-jetpack   File: network_helper.py    License: Apache License 2.0 5 votes vote down vote up
def get_public_api_network():
        net_envt = NetworkHelper._get_net_envt()
        return IPNetwork(net_envt['parameter_defaults']['ExternalNetCidr']) 
Example 23
Project: JetPack   Author: dsp-jetpack   File: network_helper.py    License: Apache License 2.0 5 votes vote down vote up
def get_private_api_network():
        net_envt = NetworkHelper._get_net_envt()
        return IPNetwork(net_envt['parameter_defaults']['InternalApiNetCidr']) 
Example 24
Project: JetPack   Author: dsp-jetpack   File: network_helper.py    License: Apache License 2.0 5 votes vote down vote up
def get_storage_network():
        net_envt = NetworkHelper._get_net_envt()
        return IPNetwork(net_envt['parameter_defaults']['StorageNetCidr']) 
Example 25
Project: JetPack   Author: dsp-jetpack   File: network_helper.py    License: Apache License 2.0 5 votes vote down vote up
def get_storage_clustering_network():
        net_envt = NetworkHelper._get_net_envt()
        return IPNetwork(net_envt['parameter_defaults']['StorageMgmtNetCidr']) 
Example 26
Project: JetPack   Author: dsp-jetpack   File: network_helper.py    License: Apache License 2.0 5 votes vote down vote up
def get_tenant_network():
        net_envt = NetworkHelper._get_net_envt()
        return IPNetwork(net_envt['parameter_defaults']['TenantNetCidr']) 
Example 27
Project: BotDigger   Author: hanzhang0116   File: BotDigger.py    License: GNU General Public License v3.0 5 votes vote down vote up
def inPrefix(IP, networkPrefixDict):
	for prefix in networkPrefixDict:
		if IPAddress(IP) in IPNetwork(prefix):
			return 1
	return 0

# check whether a domain exists 
Example 28
Project: networking-sfc   Author: openstack   File: flowclassifier_db.py    License: Apache License 2.0 5 votes vote down vote up
def _check_ip_prefix_valid(cls, ip_prefix, ethertype):
        if ip_prefix is not None:
            ip = netaddr.IPNetwork(ip_prefix)
            if ethertype == 'IPv4' and ip.version == 4:
                pass
            elif ethertype == 'IPv6' and ip.version == 6:
                pass
            else:
                raise (
                    fc_ext.FlowClassifierIpPrefixFormatConflictWithEthertype(
                        ip_prefix=ip_prefix, ethertype=ethertype
                    )
                ) 
Example 29
Project: pulseaudio-dlna   Author: masmu   File: network.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __netaddr_get_host_by_ip(ip):
    import netaddr
    host = netaddr.IPAddress(ip)
    for iface in netifaces.interfaces():
        for link in netifaces.ifaddresses(iface).get(netifaces.AF_INET, []):
            addr = link.get('addr', None)
            netmask = link.get('netmask', None)
            if addr and netmask:
                if host in netaddr.IPNetwork('{}/{}'.format(addr, netmask)):
                    logger.debug(
                        'Selecting host "{}" for IP "{}"'.format(addr, ip))
                    return addr
    logger.critical(
        '__netaddr_get_host_by_ip - No host found for IP {}!'.format(ip))
    return None 
Example 30
Project: ec2-api   Author: openstack   File: network_interface.py    License: Apache License 2.0 5 votes vote down vote up
def assign_private_ip_addresses(context, network_interface_id,
                                private_ip_address=None,
                                secondary_private_ip_address_count=None,
                                allow_reassignment=False):
    # TODO(Alex): allow_reassignment is not supported at the moment
    network_interface = ec2utils.get_db_item(context, network_interface_id)
    subnet = db_api.get_item_by_id(context, network_interface['subnet_id'])
    neutron = clients.neutron(context)
    os_subnet = neutron.show_subnet(subnet['os_id'])['subnet']
    os_port = neutron.show_port(network_interface['os_id'])['port']
    subnet_ipnet = netaddr.IPNetwork(os_subnet['cidr'])
    fixed_ips = os_port['fixed_ips'] or []
    if private_ip_address is not None:
        for ip_address in private_ip_address:
            if netaddr.IPAddress(ip_address) not in subnet_ipnet:
                raise exception.InvalidParameterValue(
                    value=str(ip_address),
                    parameter='PrivateIpAddress',
                    reason='IP address is out of the subnet range')
            fixed_ips.append({'ip_address': str(ip_address)})
    elif secondary_private_ip_address_count > 0:
        for _i in range(secondary_private_ip_address_count):
            fixed_ips.append({'subnet_id': os_subnet['id']})
    try:
        neutron.update_port(os_port['id'],
                            {'port': {'fixed_ips': fixed_ips}})
    except neutron_exception.IpAddressGenerationFailureClient:
        raise exception.InsufficientFreeAddressesInSubnet()
    except neutron_exception.IpAddressInUseClient:
        msg = _('Some of %(addresses)s is assigned, but move is not '
                'allowed.') % {'addresses': private_ip_address}
        raise exception.InvalidParameterValue(msg)
    except neutron_exception.BadRequest as ex:
        # NOTE(ft):AWS returns PrivateIpAddressLimitExceeded, but Neutron does
        # general InvalidInput (converted to BadRequest) in the same case.
        msg = _('Specified network interface parameters are invalid. '
                'Reason: %(reason)s') % {'reason': ex.message}
        raise exception.InvalidParameterValue(msg)
    return True