将IP列表与另一个IP列表或IP范围进行比较 [英] Compare IP List to another IP List or IP Range

查看:307
本文介绍了将IP列表与另一个IP列表或IP范围进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个python项目,该项目扫描ip范围(即x.y.z.0/24)并返回在线主机列表.它会将在线主机列表保存到仅包含IP的文件(即['192.168.0.1','192.168.0.2','192.168.0.8',...]. d想要将此在线主机列表与IP范围进行比较,以验证这些计算机是否可以淘汰其他设备.我有一个可供使用的计算机的DHCP保留列表.是否有一种简单的方法来执行此操作并更新onHosts列表?

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?

推荐答案

这里是您可以尝试的建议解决方案(虽然有点肿,但希望稍后再进行编辑)

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]))

这篇关于将IP列表与另一个IP列表或IP范围进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆