Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_ipset_supersets_and_subsets():
s1 = IPSet(['192.0.2.0/24', '192.0.4.0/24'])
s2 = IPSet(['192.0.2.0', '192.0.4.0'])
assert s1.issuperset(s2)
assert s2.issubset(s1)
assert not s2.issuperset(s1)
assert not s1.issubset(s2)
ipv4_addr_space = IPSet(['0.0.0.0/0'])
private = IPSet(['10.0.0.0/8', '172.16.0.0/12', '192.0.2.0/24',
'192.168.0.0/16', '239.192.0.0/14'])
reserved = IPSet(['225.0.0.0/8', '226.0.0.0/7', '228.0.0.0/6', '234.0.0.0/7',
'236.0.0.0/7', '238.0.0.0/8', '240.0.0.0/4'])
unavailable = reserved | private
available = ipv4_addr_space ^ unavailable
assert [tuple(map(str, (cidr, cidr[0], cidr[-1]))) for cidr in available.iter_cidrs()] == [
('0.0.0.0/5', '0.0.0.0', '7.255.255.255'),
def test_ipset_comparison():
s1 = IPSet(['fc00::/2'])
s2 = IPSet(['fc00::/3'])
assert s1 > s2
assert not s1 < s2
assert s1 != s2
def test_ipset_member_insertion_and_deletion():
s1 = IPSet()
s1.add('192.0.2.0')
assert s1 == IPSet(['192.0.2.0/32'])
s1.remove('192.0.2.0')
assert s1 == IPSet([])
s1.add(IPRange("10.0.0.0", "10.0.0.255"))
assert s1 == IPSet(['10.0.0.0/24'])
s1.remove(IPRange("10.0.0.128", "10.10.10.10"))
assert s1 == IPSet(['10.0.0.0/25'])
def parse_cidr_list(cidrs):
try:
return netaddr.IPSet(
[c for c in cidrs.split(',') if c.strip()])
except Exception as e:
LOG.warning('Failed to parse CIDRs: %(cidr)s: %(exc)s',
{'cidr': cidrs, 'exc': e})
return None
def ipset(nets):
v4nets = netaddr.IPSet()
v6nets = netaddr.IPSet()
for net in nets:
ipNetwork = netaddr.IPNetwork(net)
parts = str(ipNetwork).split("/")
ip = parts[0]
mask = parts[1]
if netaddr.valid_ipv4(ip) and int(mask) <= 32:
v4nets.add(ipNetwork)
elif netaddr.valid_ipv6(ip) and int(mask) <= 128:
v6nets.add(ipNetwork)
return v4nets, v6nets
def load_ips(self, file_of_systems):
# Check to make sure file given is a valid file
if os.path.isfile(file_of_systems):
# read in IPs from a file
with open(file_of_systems, "r") as system_file:
justmetadata_system_list = system_file.readlines()
total_systems = 0
# Cast each IP its own object
for system in justmetadata_system_list:
if "/" in system:
try:
for ip in netaddr.IPSet([system]):
ip = str(ip)
activated_system_object = ip_object.IP_Information(ip)
if ip in self.system_objects:
self.system_objects[ip][1] = self.system_objects[ip][1] + 1
total_systems += 1
else:
self.system_objects[ip] = [activated_system_object, 1]
total_systems += 1
except netaddr.core.AddrFormatError:
print helpers.color("[*] Error: Bad IP CIDR range detected! (" + str(system).strip() + ")", warning=True)
continue
else:
activated_system_object = ip_object.IP_Information(system.strip())
if system in self.system_objects:
self.system_objects[system][1] = self.system_objects[system][1] + 1
total_systems += 1
def _compact_subnetpool_prefix_list(self, prefix_list):
"""Compact any overlapping prefixes in prefix_list and return the
result
"""
ip_set = netaddr.IPSet()
for prefix in prefix_list:
ip_set.add(netaddr.IPNetwork(prefix))
ip_set.compact()
return [x.cidr for x in ip_set.iter_cidrs()]
Get the first unused IP subnetwork in the 10.0.0.0 net.
The method queries all networks that are reachable by the currently
known network interfaces.
Search starts at 10.1.1.0.
TODO Enable to select range for subnets, e.g., (10.2.3.0, 10.42.6.0)
TODO Method could be refactored to be more pythonic
:returns: First valid IP address in the subnet/CIDR_Mask as string
:raises: RuntimeError if out of available networks
'''
# Get all used subnets
ipdb = pyroute2.IPDB()
ipset = netaddr.IPSet()
try:
for ifname, vals in ipdb.by_name.items():
ips = Network._if_to_ip(vals, all_ips=True)
for ipaddr, cidr in [(x, y) for x, y in ips if x.startswith('10.')]:
network = netaddr.IPNetwork('%s/%s' % (ipaddr, cidr))
ipset.add(network)
finally:
ipdb.release()
# Find unused subnet
for oct3 in range(1, 256):
for oct2 in range(1, 256):
network = '10.%d.%d.1/24' % (oct2, oct3)
if ipset.isdisjoint(netaddr.IPSet([network])):
logging.debug('Found free /24 subnet: %s', network)
return network
def _ip_address_to_subnet_id(ip_addr, vn_obj, memo_req):
subnets_info = memo_req['subnets'].get(vn_obj.uuid)
for subnet_info in subnets_info or []:
if (netaddr.IPAddress(ip_addr) in
netaddr.IPSet([subnet_info['cidr']])):
return subnet_info['id']
ipam_refs = vn_obj.get_network_ipam_refs()
for ipam_ref in ipam_refs or []:
subnet_vncs = ipam_ref['attr'].get_ipam_subnets()
for subnet_vnc in subnet_vncs:
cidr = '%s/%s' % (subnet_vnc.subnet.get_ip_prefix(),
subnet_vnc.subnet.get_ip_prefix_len())
if netaddr.IPAddress(ip_addr) in netaddr.IPSet([cidr]):
return subnet_vnc.subnet_uuid
"""
# Auto allocate the pool around gateway_ip
net = netaddr.IPNetwork(cidr)
ip_version = net.version
first = netaddr.IPAddress(net.first, ip_version)
last = netaddr.IPAddress(net.last, ip_version)
if first == last:
# handle single address subnet case
return [netaddr.IPRange(first, last)]
first_ip = first + 1
# last address is broadcast in v4
last_ip = last - (ip_version == 4)
if first_ip >= last_ip:
# /31 lands here
return []
ipset = netaddr.IPSet(netaddr.IPRange(first_ip, last_ip))
if gateway_ip:
ipset.remove(netaddr.IPAddress(gateway_ip, ip_version))
return list(ipset.iter_ipranges())