Given an IP range, how can code to subtract an IP address or IP address range from that range?
Example 1:
original_range = '10.182.110.0/24'
# Same as '10.182.110.0-10.182.110.255'
subtract_range = '10.182.110.51-10.182.254'
> diff_range = '10.182.110.0-10.182.110.50, 10.182.110.255'
Example 2:
original_range = '10.10.20.0-10.10.20.20'
subtract_range = '10.10.20.16'
> diff_range = '10.10.20.10-10.10.20.15, 10.10.20.17-10.10.20.20'
Example 3:
original_range = '10.170.0.0/16'
# Same as '10.170.0.0-10.170.31.255'
subtract_range = '10.170.20.16'
> diff_range = '10.170.0.0-10.170.20.15, 10.170.20.17-10.170.31.255'
Here are the functions I use to do this (moving back and forth between the format Qualys uses and instances of the objects provided by ipaddr:
For your specific examples, I would use the functions above and the ‘exclude_address’ method in instances of ipaddr.IPNetwork objects to write a new function that accepts the original_range and subtract_range inputs, returning a list of ipaddr objects (or an ip_string in Qualys’s expected format usingthe ip_list_to_ip_string function above). The only tricky part will be that when you run ‘ip_string_to_cidr(exclude_list)’ you’ll receive a list of IPNetwork objects that need to be subtracted from ‘original_range’.
If you need more help, I can probably throw together some kind of exclude_ips function, as I’ll need it at some point, just let me know.