【问题标题】:get unused security list from all regions thru boto3通过 boto3 从所有区域获取未使用的安全列表
【发布时间】:2019-04-14 06:18:00
【问题描述】:

我正在尝试从所有地区获取未使用的 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

【问题讨论】:

  • 您提取了该区域,但没有在任何地方使用它。要在代码中切换区域,需要使用 boto3.session

标签: boto3 aws-security-group


【解决方案1】:

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,谢谢。

【讨论】:

  • 非常感谢它按预期为我工作,我明白了我错了再次感谢
  • 嘿,它按预期工作,但我需要在 EC2、RDS、ELB 的基础上找到未使用的 SG,现在我只检查那些未附加到 EC2 但我需要列表的安全组所有未连接到任何 EC2、RDS、ELB 的 SG
  • 响应 = boto3.client('rds').describe_db_security_groups()
  • 响应 = boto3.client('elb').describe_load_balancers()
  • 谢谢,如何将我的输出放在一个 csv 文件中,请告诉我?
猜你喜欢
  • 1970-01-01
  • 2019-03-10
  • 1970-01-01
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 2018-12-13
相关资源
最近更新 更多