遍历两个列表

Iterate through two list

import ipaddress
from ipaddress import ip_network

MY_VPC_SUBNETS = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]
MY_SG_IPS = ["172.16.1.34/32", "10.16.0.0/12", "172.16.12.0/28", "10.15.90.2/32", "60.20.15.0/24","76.0.0.0/8"]

security_group_rules=[]
allowed_ips=[]

for network in MY_VPC_SUBNETS:
    internal_network = ipaddress.ip_network(network)
    allowed_ips.append(internal_network)


for rule_ip in MY_SG_IPS:
    sg_ip = ipaddress.ip_network(rule_ip)
    security_group_rules.append(sg_ip)


security_group_rules.sort()
allowed_ips.sort()

for x in security_group_rules:
    for y in allowed_ips:
        a = ip_network(x)
        b = ip_network(y)

        if a.subnet_of(b):
            print(a)

所以,这可以工作并打印 MY_SG_IPS 中的 IP,这些 IP 位于 MY_VPC_SUBNETS 的 ips 子网中,但我无法列出不属于列表中任何子网的 ips MY_VPC_SUBNETS.

有什么想法吗?

您可以使用 memoization 来跟踪 IP 是否被视为有效。

使用字典来跟踪每个IP是否被认为有效如下...

# Use dict to track who is in a subnet
visited = { ip: False for ip in allowed_ips }

for x in security_group_rules:
    for y in allowed_ips:
        a = ip_network(x)
        b = ip_network(y)

        if a.subnet_of(b):
            visited[y] = True;
            print(a)
            
# Check which IPs are not visited
ips_not_in_subnet = [x for x in visited if not visited[x]]