多字符串比较

时间:2021-06-23 00:42:12

标签: python

我在 restapi 中创建了一个调用以将结果打印在一个数组中,但我需要在保存此结果之前比较这些数据,例如:

for id in ids:
    try:
        now = datetime.datetime.now()
        token, tokenExpireDate = checkTokenExpireDate(apiUrl, client_id, client_secret, token, now, tokenExpireDate) 
        data = getHostDetails(apiUrl, token, id)['resources'][0]
        local_ip = data['local_ip']
        allowed_range_ip = ['10.20.*', '10.10.*', '172.12.*']
        if local_ip in allowed_range_ip:
            print(local_ip)
        else:
            print(local_ip)
    except Exception as e:
        print({'exception': e, 'id': id})

我想将 allowed_range_iplocal_ip 进行比较,如果 local_ipallowed_range_ip 保存在数组中为真,我该怎么做? 我是使用 python 的新手,所以放轻松 :)

编辑: 示例输出脚本(一些随机 ip),我只想打印类似于 allowed_range_ip 的 ip:

    10.160.20.02
    172.17.0.9
    10.255.250.68
    10.80.10.20

1 个答案:

答案 0 :(得分:5)

Python 的内置 ipaddress 模块使这变得简单。您创建一个 ip_network 对象,然后您可以查看给定的 ip_address 是否在该网络中。例如:

from ipaddress import ip_address, ip_network

allowed_range_ip = [
    ip_network("10.20.0.0/16"),
    ip_network("10.10.0.0/16"),
    ip_network("172.12.0.0/16"),
]

local_ip1 = ip_address('10.20.30.40')
print(any(local_ip1 in net for net in allowed_range_ip))

local_ip2 = ip_address('10.21.30.40')
print(any(local_ip2 in net for net in allowed_range_ip))
相关问题