Skip to content

Instantly share code, notes, and snippets.

@thesubtlety
Last active Oct 15, 2019
Embed
What would you like to do?
Random utilities to work with IP hosts, ranges, CIDR ranges
import netaddr, ipaddress
def file_to_array(fname):
with open(fname) as f:
farr = [l.strip() for l in f if l.strip()]
return farr
def cidrs_to_hosts(input_arr):
output_arr = []
for e in input_arr:
for host in ipaddress.ip_network(e, False):
output_arr.append(host.compressed)
output_arr = list(set(output_arr))
print("Host list contains {} IPs".format(len(output_arr)))
return output_arr
def merge_cidrs(cidr_array):
merged_arr = []
for each in netaddr.cidr_merge(cidr_array):
merged_arr.append(str(each))
print("Merged from {} to {} ranges".format(len(cidr_array),len(merged_arr)))
return merged_arr
def count_hosts_in_array(arr):
a = []
for e in arr:
for host in ipaddress.ip_network(e, False):
a.append(host.compressed)
print(len(list(set(a))))
def check_host_in_list(ip, arr):
a = []
for e in arr:
for host in ipaddress.ip_network(e, False):
a.append(host.compressed)
a = list(set(a))
if ip in a:
print("{} is in the list".format(ip))
else:
print("{} is NOT in the list".format(ip))
def fromtorange_to_cidrs(arr):
if isinstance(arr, str):
arr = [e.strip() for e in arr.split(",")]
out_array = []
for range in arr:
if "-" in range:
first, last = range.split("-")
ip_merged = netaddr.cidr_merge(netaddr.iter_iprange(first.strip(),last.strip()))
if isinstance(ip_merged, list):
for r in ip_merged:
out_array.append(str(r))
else:
out_array.append(str(ip_merged))
else:
out_array.append(range)
return out_array
def print_hosts_to_file(fname, arr):
with open(fname,"w") as f:
a = []
for r in arr:
for host in ipaddress.ip_network(r, False):
a.append(host.compressed)
ips = list(set(a))
for ip in ips:
f.write("%s\n" % ip)
def masks_to_cidrs(arr):
return [str(ipaddress.IPv4Network(nm)) for nm in arr if nm.strip()]
# Use sets to determine if one host is in another
list_one_minus_list_two = list(list_one.difference(list_two)) # returns list_one less anything in list_two, switch for viceversa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment