You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Boto3筛选含0.0.0.0/0入站规则的安全组时过滤器报错求助

解决方法

你遇到的问题是混淆了不同EC2 API的过滤器名称:ip-permission.cidr是describe_security_groups接口的过滤器,而describe_security_group_rules接口使用的是另一套过滤规则。

正确的describe_security_group_rules代码

要筛选入站规则允许0.0.0.0/0的安全组规则,需要使用cidr过滤器匹配IP段,同时用direction过滤器限定为入站(ingress):

import boto3

client = boto3.client('ec2')
response = client.describe_security_group_rules(
    Filters=[
        {'Name': 'cidr', 'Values': ['0.0.0.0/0']},
        {'Name': 'direction', 'Values': ['ingress']}
    ]
)

# 遍历输出结果
for rule in response['SecurityGroupRules']:
    print(f"安全组ID: {rule['GroupId']}, 规则详情: {rule}")

另一种方案:使用describe_security_groups

如果你需要直接获取包含这类规则的完整安全组信息,也可以用你最初参考的过滤器,但要调用describe_security_groups接口:

import boto3

client = boto3.client('ec2')
response = client.describe_security_groups(
    Filters=[
        {'Name': 'ip-permission.cidr', 'Values': ['0.0.0.0/0']}
    ]
)

# 输出安全组基本信息
for sg in response['SecurityGroups']:
    print(f"安全组ID: {sg['GroupId']}, 名称: {sg['GroupName']}")

内容的提问来源于stack exchange,提问作者Satyashil Deshpande

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 21:12:43