Compare IP List to another IP List or IP Range

2019-08-01 16:37发布

问题:

I've created a python project that scans an ip range (ie. x.y.z.0/24) and returns a list of online hosts. It saves the online hosts list to file with just the ip's (ie ['192.168.0.1', '192.168.0.2', '192.168.0.8',...]. I'm having trouble with this next step. I'd like to compare this online hosts list to an IP range to verify that these are computers to eliminate other devices. I have a DHCP Reservation List for computers that I can use. Is there a simple way to do this and update the onHosts list?

回答1:

Here is proposed solution you can try (it is a little bit bloated but I will edit it later hopefully)

def get_range(str_num):
    """ Converts string representation of number or range into (min,max) tuple """
    try:
        num = int(str_num)
        return num, num
    except ValueError:
        min_, max_ = str_num.split('-')
        return int(min_), int(max_)

def host_in_range(host, host_range):
    """ Checks whether given host belongs to given range (both are range representation """
    #print(*zip(host, host_range))
    for (min_h, max_h), (min_r, max_r) in zip(host, host_range):
        if (min_h < min_r) or (max_h > max_r): return False
    return True


if __name__ == "__main__":

    hosts_str = ['192.168.0.1', '192.168.0.10', '0.168.0.0', '192.168.1.10', '192.168.0.255']
    hosts = [x.split('.') for x in hosts_str]
    hosts = [[get_range(x) for x in elem] for elem in hosts]

    host_ranges_str = ['0-255.168.0.0-254', '192.168.2-5.0-255']
    host_ranges = [x.split('.') for x in host_ranges_str]
    host_ranges = [[get_range(x) for x in elem] for elem in host_ranges]

    for x in range(5):
        print(hosts_str[x], "in range", host_ranges_str[0], host_in_range(hosts[x], host_ranges[0]))