python - boto3 列出与 ec2 实例关联的安全组

标签 python amazon-ec2 boto3

是否可以使用 boto3 列出与 EC2 实例关联的所有安全组? ?如果是这样,这是怎么做的?

我尝试了以下方法,但他们没有做我想做的事:

for region in regions:
    client = boto3.client('ec2', region_name=region)
    try:
        payload = client.describe_security_groups(Filters=[{'Name': 'vpc-id', 'Values': ['vpc-*']}])
        for sg in payload["SecurityGroups"]:
            if sg["Description"] != "default VPC security group":
                resp = client.describe_security_group_references(DryRun=False, GroupId=[sg["GroupId"]])
                print resp

    except Exception as E:
        print region, E
        continue
for region in regions:
    client = boto3.client('ec2', region_name=region)
    try:
        payload = client.describe_security_groups(Filters=[{'Name': 'vpc-id', 'Values': ['vpc-*']}])
        for sg in payload["SecurityGroups"]:
            if sg["Description"] != "default VPC security group":
                sg = json.dumps(sg)
                pp(sg)
                # x = requests.post(url=sumocollector, data=sg)
                # print x.status_code

    except Exception as E:
        print region, E
        continue

最佳答案

如果您正在寻找每个实例的 SG 列表,那么我会做 describe_instances反而:

for region in regions:
    client = boto3.client('ec2', region_name=region)
    try:
        response = client.describe_instances()
        for reservation in response['Reservations']:
            for instance in reservation['Instances']:
                print("Instance: " + instance['InstanceId'])
                for securityGroup in instance['SecurityGroups']:
                    print("SG ID: {}, Name: {}".format(securityGroup['GroupId'], securityGroup['GroupName']))

    except Exception as E:
        print(region, E)
        continue

关于python - boto3 列出与 ec2 实例关联的安全组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55913141/

相关文章:

python - conda 不被识别为内部或外部命令、可运行程序或批处理文件

amazon-web-services - 转移 AWS 促销积分

aws-lambda - 使用排序键删除 DynamoDb

Python Boto3 AWS 分段上传语法

python - OpenCV 在 Raspberry Pi 上单击鼠标关闭窗口

python - ValueError 尝试遍历

python - 如何将 association_proxy 和 ordering_list 与 SQLAlchemy 一起正确使用

amazon-web-services - 通过 Ubuntu 堡垒到私有(private)子网中的 EC2 实例的 SSH 隧道

docker - 如何允许访问 EC2 实例上的 docker 容器

python - 如何在不尝试任何身份验证的情况下获取 boto3 STS 客户端?