Python netaddr.IPNetwork() Examples
The following are 30
code examples of netaddr.IPNetwork().
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: google.py From minemeld-core with Apache License 2.0 | 6 votes |
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 #2
Source File: CloudConnector.py From im with GNU General Public License v3.0 | 6 votes |
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 #3
Source File: vSphere.py From im with GNU General Public License v3.0 | 6 votes |
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: utils_net.py From avocado-vt with GNU General Public License v2.0 | 6 votes |
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 #5
Source File: __init__.py From privacyidea with GNU Affero General Public License v3.0 | 6 votes |
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 #6
Source File: data_utils.py From tempest-lib with Apache License 2.0 | 6 votes |
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 #7
Source File: ipsec.py From neutron-vpnaas with Apache License 2.0 | 6 votes |
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 #8
Source File: validator.py From ec2-api with Apache License 2.0 | 6 votes |
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 #9
Source File: ipsec.py From neutron-vpnaas with Apache License 2.0 | 6 votes |
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 #10
Source File: px.py From px with MIT License | 6 votes |
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 #11
Source File: impl_eni.py From os-net-config with Apache License 2.0 | 6 votes |
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 #12
Source File: discover_nodes.py From JetPack with Apache License 2.0 | 6 votes |
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 #13
Source File: google.py From minemeld-core with Apache License 2.0 | 6 votes |
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 #14
Source File: cloudfrunt.py From cloudfrunt with MIT License | 6 votes |
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 #15
Source File: ipop.py From minemeld-core with Apache License 2.0 | 6 votes |
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 #16
Source File: azure.py From minemeld-core with Apache License 2.0 | 6 votes |
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 #17
Source File: base.py From ScoutSuite with GNU General Public License v2.0 | 6 votes |
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 #18
Source File: config_dashboard.py From JetPack with Apache License 2.0 | 6 votes |
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 #19
Source File: o365.py From minemeld-core with Apache License 2.0 | 5 votes |
def _analyze_item(self, item): result = [] base_value = {} for wka in O365_API_FIELDS: if wka in item: base_value['o365_{}'.format(wka)] = item[wka] if self.disable_integrations and 'o365_notes' in base_value: if 'integration' in base_value['o365_notes'].lower(): return result for url in item.get('urls', []): value = base_value.copy() value['type'] = 'URL' result.append([url, value]) for ip in item.get('ips', []): try: parsed = netaddr.IPNetwork(ip) except (netaddr.AddrFormatError, ValueError): LOG.error('{} - Unknown IP version: {}'.format(self.name, ip)) continue value = base_value.copy() if parsed.version == 4: value['type'] = 'IPv4' elif parsed.version == 6: value['type'] = 'IPv6' result.append([ip, value]) return result
Example #20
Source File: dag.py From minemeld-core with Apache License 2.0 | 5 votes |
def _validate_ip(self, indicator, value): type_ = value.get('type', None) if type_ not in ['IPv4', 'IPv6']: LOG.error('%s - invalid indicator type, ignored: %s', self.name, type_) self.statistics['ignored'] += 1 return if '-' in indicator: i1, i2 = indicator.split('-', 1) if i1 != i2: LOG.error('%s - indicator range must be equal, ignored: %s', self.name, indicator) self.statistics['ignored'] += 1 return indicator = i1 try: address = netaddr.IPNetwork(indicator) except netaddr.core.AddrFormatError as e: LOG.error('%s - invalid IP address received, ignored: %s', self.name, e) self.statistics['ignored'] += 1 return if address.size != 1: LOG.error('%s - IP network received, ignored: %s', self.name, address) self.statistics['ignored'] += 1 return if type_ == 'IPv4' and address.version != 4 or \ type_ == 'IPv6' and address.version != 6: LOG.error('%s - IP version mismatch, ignored', self.name) self.statistics['ignored'] += 1 return return address
Example #21
Source File: visa.py From minemeld-core with Apache License 2.0 | 5 votes |
def _detect_ip_version(self, ip_addr): try: parsed = IPNetwork(ip_addr) except (AddrFormatError, ValueError): LOG.error('{} - Unknown IP version: {}'.format(self.name, ip_addr)) return None if parsed.version == 4: return 'IPv4' if parsed.version == 6: return 'IPv6' return None
Example #22
Source File: threatconnect.py From minemeld-core with Apache License 2.0 | 5 votes |
def _detect_ip_version(self, ip_addr): try: parsed = IPNetwork(ip_addr) except (AddrFormatError, ValueError): LOG.error('{} - Unknown IP version: {}'.format(self.name, ip_addr)) return None if parsed.version == 4: return 'IPv4' if parsed.version == 6: return 'IPv6' return None
Example #23
Source File: types.py From octavia with Apache License 2.0 | 5 votes |
def validate(value): """Validates whether value is an IPv4 or IPv6 CIDR.""" try: return str(netaddr.IPNetwork(value).cidr) except (ValueError, netaddr.core.AddrFormatError): error = 'Value should be IPv4 or IPv6 CIDR format' raise ValueError(error)
Example #24
Source File: scanner.py From PyCat with GNU General Public License v3.0 | 5 votes |
def udp_sender(subnet,magic_message): sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for ip in IPNetwork(subnet): try: sender.sendto(magic_message,("%s" % ip,65212)) except: pass
Example #25
Source File: create_subinterface.py From restconf-examples with Apache License 2.0 | 5 votes |
def main(): parser = argparse.ArgumentParser() parser.add_argument('vlan', help = "VLAN number (1-4094)", type=int) parser.add_argument('prefix', help = "IPv4 or IPv6 prefix") parser.add_argument('--insecure', '-k', action='store_true', help = "relax SSL verification") parser.add_argument('--interface', '-i', default=BASE, help = "interface name to use") parser.add_argument('--user', '-u', default=USER, help = "user name on remote host") parser.add_argument('--password', '-p', default=PASS, help = "password on remote host") parser.add_argument('--port', '-P', default=PORT, help = "port on remote host") parser.add_argument('--host', '-H', default=HOST, help = "remote host") args = parser.parse_args() # check for valid VLAN ID if args.vlan < 1 or args.vlan > 4094: parser.print_usage() print ("invalid VLAN ID %s" % str(args.vlan)) return -1 # check for valid prefix try: ip = netaddr.IPNetwork(args.prefix) except netaddr.core.AddrFormatError as e: parser.print_usage() print(e) return -1 # insecure? if args.insecure: requests.packages.urllib3.disable_warnings() return create_vlan(args.host, args.port, args.user, args.password,args.interface, args.vlan, ip, args.insecure)
Example #26
Source File: arearange.py From genielibs with Apache License 2.0 | 5 votes |
def build_config(self, apply=True, attributes=None, unconfig=False, **kwargs): assert not kwargs, kwargs attributes = AttributesHelper(self, attributes) configurations = CliConfigBuilder(unconfig=unconfig) # router ospf 1 # range 192.168.1.0 255.255.255.0 # range 192.168.1.0 255.255.255.0 advertise # range 192.168.1.0 255.255.255.0 not-advertise if attributes.value('area_range_prefix'): # + range {area_range_prefix} if re.search("\/", attributes.value('area_range_prefix')): range_val = IPNetwork(attributes.value('area_range_prefix')) prefix = str(range_val.ip) netmask = str(range_val.netmask) ar_str = ' range {} {}'.format(prefix, netmask) else: ar_str = ' range {area_range_prefix}' # + advertise # + not-advertise if attributes.value('area_range_advertise') is True: ar_str += ' advertise' elif attributes.value('area_range_advertise') is False: ar_str += ' not-advertise' configurations.append_line(attributes.format(ar_str)) return str(configurations)
Example #27
Source File: Ingestor.py From armory with GNU General Public License v3.0 | 5 votes |
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 #28
Source File: create_static.py From restconf-examples with Apache License 2.0 | 5 votes |
def main(): """Main method to create static route.""" parser = argparse.ArgumentParser() parser.add_argument('route', help="static route (IPv4)") parser.add_argument('nexthop', help="nexthop for (Interface or IPv4)") parser.add_argument('--insecure', '-k', action='store_true', help="relax SSL verification") parser.add_argument('--user', '-u', default=USER, help="user name on remote host") parser.add_argument('--password', '-p', default=PASS, help="password on remote host") parser.add_argument('--port', '-P', default=PORT, help="port on remote host") parser.add_argument('--host', '-H', default=HOST, help="remote host") args = parser.parse_args() # check for valid prefix try: ip = netaddr.IPNetwork(args.route) except netaddr.core.AddrFormatError as e: parser.print_usage() print(e) return -1 # insecure? if args.insecure: requests.packages.urllib3.disable_warnings() return create_static(args.host, args.port, args.user, args.password, args.route, args.nexthop, args.insecure)
Example #29
Source File: configuration_data_randomizer.py From restconf-examples with Apache License 2.0 | 5 votes |
def random_route(base, length): """Return a random route based on a base prefix and target prefix length.""" ip = netaddr.IPNetwork(base) routes = list(ip.subnet(length)) return random.choice(routes)
Example #30
Source File: network_helper.py From f5-openstack-agent with Apache License 2.0 | 5 votes |
def arp_delete_by_subnet(self, bigip, subnet=None, mask=None, partition=const.DEFAULT_PARTITION): if not subnet: return [] mask_div = subnet.find('/') if mask_div > 0: try: rd_div = subnet.find('%') if rd_div > -1: network = netaddr.IPNetwork( subnet[0:mask_div][0:rd_div] + subnet[mask_div:]) else: network = netaddr.IPNetwork(subnet) except Exception as exc: LOG.error('arp_delete_by_subnet', exc.message) return [] elif not mask: return [] else: try: rd_div = subnet.find('%') if rd_div > -1: network = netaddr.IPNetwork(subnet[0:rd_div] + '/' + mask) else: network = netaddr.IPNetwork(subnet + '/' + mask) except Exception as exc: LOG.error('ARP', exc.message) return [] return self._arp_delete_by_network(bigip, partition, network)