通过boto3从所有区域获取未使用的安全列表

时间:2018-11-11 07:33:32

标签: boto3 aws-security-group

我正在尝试从所有地区获取未使用的SG,但是它无法正常工作。

我尝试了以下代码

#!/usr/bin/env python
import boto3

ec2 = boto3.resource('ec2')
regions = ec2.describe_regions().get('Regions',[])
for region in regions:
  reg=region['RegionName']

sgs = list(ec2.security_groups.all())
insts = list(ec2.instances.all())

all_sgs = set([sg.group_name for sg in sgs])
all_inst_sgs = set([sg['GroupName'] for inst in insts for sg in inst.security_groups])
unused_sgs = all_sgs - all_inst_sgs

print 'Total SGs:', len(all_sgs)
print 'SGS attached to instances:', len(all_inst_sgs)
print 'Orphaned SGs:', len(unused_sgs)
print 'Unattached SG names:', unused_sgs

1 个答案:

答案 0 :(得分:0)

describe_regions是ec2客户端的功能,而不是ec2资源。试试这个:

#!/usr/bin/env python
import boto3

ec2 = boto3.client('ec2')
regions = ec2.describe_regions().get('Regions',[])
for region in regions:
  reg=region['RegionName']

但是您没有以任何方式使用区域名称。以下代码在各个区域中进行迭代,在每个区域中设置新的ec2资源,然后重复扫描。

#!/usr/bin/env python
import boto3


ec2Client = boto3.client('ec2')
regions = ec2Client.describe_regions().get('Regions',[])
for region in regions:
    reg=region['RegionName']
    print ('Checking region {}'.format(reg))

    ec2 = boto3.resource('ec2', region_name=reg)

    sgs = list(ec2.security_groups.all())
    insts = list(ec2.instances.all())

    all_sgs = set([sg.group_name for sg in sgs])
    all_inst_sgs = set([sg['GroupName'] for inst in insts for sg in inst.security_groups])
    unused_sgs = all_sgs - all_inst_sgs

    print ('    Total SGs:', len(all_sgs))
    print ('    SGS attached to instances:', len(all_inst_sgs))
    print ('    Orphaned SGs:', len(unused_sgs))
    print ('    Unattached SG names:', unused_sgs)

在测试时,我发现我有很多未使用的SG,谢谢。