def IPRange(Range, range_temp, language):
myranges_now = open(range_temp).read().rsplit()
if Range not in myranges_now:
r_f = open(range_temp, 'a')
r_f.write(Range + '\n')
r_f.close()
if len(Range.rsplit('.')) is 7 and '-' in Range and '/' not in Range:
if len(Range.rsplit('-')) is 2:
start_ip, stop_ip = Range.rsplit('-')
if isIP(start_ip) is True and isIP(stop_ip) is True:
return iprange_to_cidrs(start_ip, stop_ip)
else:
return []
else:
return []
elif len(Range.rsplit('.')) is 4 and '-' not in Range and '/' in Range:
return IPNetwork(Range)
else:
return []
else:
warn(messages(language, 49))
return []
python类iprange_to_cidrs()的实例源码
def come_up_subnet(neutron_subnets, size):
"""Come ups subnets with specific size
@param neutron_subnets: List of neutron subnets
@type neutron_subnets: `list(client_factory.Accessible)`
@param size: Size of future subnet
@type size: `int`
"""
log.info("Start generating of subnets")
subnets = []
for neutron_subnet in neutron_subnets:
first = netaddr.IPAddress(netaddr.IPNetwork(neutron_subnet.cidr).first)
last = netaddr.IPAddress(netaddr.IPNetwork(neutron_subnet.cidr).last)
subnets.extend([first, last])
subnets.sort()
subnets.insert(0, netaddr.IPAddress("192.0.0.0"))
subnets.append(netaddr.IPAddress("192.255.255.255"))
max_size = 0
for start, end in zip(subnets[::2], subnets[1::2]):
space_range = list(netaddr.IPRange(start, end))
if str(start) != "192.0.0.0":
space_range = space_range[1:]
elif str(end) != "192.255.255.255":
space_range = space_range[:-1]
space_size = len(space_range)
if space_size > max_size:
max_size = space_size
start_ip = str(start)
end_ip = str(end)
if space_size >= size:
return netaddr.iprange_to_cidrs(space_range[0],
space_range[size - 1])[0]
return netaddr.iprange_to_cidrs(start_ip, end_ip)[0]
def get_inet_num(search_term):
"""
Get intetnums for a domain
:param search_term: keywork without dots, no domains are allowed. domain.com -> invalid |---| domain -> valid
:type search_term: str
:return: iterable with IP/CIDR notation or None
:rtype: list(str) | None
"""
# Disable request logging
requests_log = logging.getLogger("requests")
requests_log.addHandler(logging.NullHandler())
requests_log.propagate = False
# Search the RIPE database
# There is an issue with RIPE. When making a request and including
# the type-filter inetnum, the JSON response also includes other types.
request = requests.get('http://rest.db.ripe.net/search.json', params={
'query-string': search_term,
'type-filter': 'inetnum'
})
json_results = json.loads(request.text)
try:
# Filter any object that doesn't have the type 'inetnum'
ranges = [x['primary-key']['attribute'][0]['value']
for x in json_results['objects']['object']
if x['type'] == 'inetnum']
except KeyError:
return None
# Turn the IP range string into CIDR
cidrs = []
for _range in ranges:
_range = _range.split(' - ');
cidrs.append(netaddr.iprange_to_cidrs(_range[0], _range[1]))
results = set()
# Print the CIDR's
for cidr in cidrs:
results.add(str(cidr[0]))
return results