首页 > 解决方案 > 如何检索所有安全组 ID 并将它们保存到可迭代列表中?

问题描述

我想遍历所有安全组,并在任何端口上找到对互联网开放的规则。

# This script is for identifying security groups with rules with open to internet.


import boto3

def inspect(thing):
        print("Funcs: "+str(dir(thing)))
        for key in list(thing):
                print("   "+key+": "+str(thing[key]))

ec2 = boto3.resource('ec2')
security_group = ec2.SecurityGroup('id')
type = inspect(security_group)
print ("type")

for i in security_group:
    try:
        response = client.describe_security_groups(GroupIds=[i])
        print(response)
    except ClientError as e:
        print(e)

标签: amazon-web-servicesboto3aws-security-group

解决方案


您可以使用 EC2 低级客户端来获取所有安全组。describe_security_groups()返回一个字典对象作为响应。所以你只需要迭代它来评估你的安全组规则。

import boto3

client = boto3.client('ec2')
response = client.describe_security_groups()

for sg in response['SecurityGroups']:
    for ingressrule in sg['IpPermissions']:
        print(ingressrule.get('FromPort', -1))
        print(ingressrule.get('ToPort', -1))
        for iprange in ingressrule['IpRanges']:
            print(iprange.get('CidrIp', -1))

您还可以使用过滤器仅列出具有广泛访问权限的入口规则:

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

推荐阅读