使用 Python 和 Boto3 查找并验证 AWS 中未使用的安全组

wufei123 2025-01-05 阅读:65 评论:0
有效管理 aws 安全组对于维护安全且经济高效的云环境至关重要。安全组是 aws 网络安全的重要组成部分,但随着时间的推移,未使用的安全组会不断累积。这些未使用的组不仅会使您的环境变得混乱,还可能带来安全风险或不必要地增加成本。 在本文...

使用 python 和 boto3 查找并验证 aws 中未使用的安全组

有效管理 aws 安全组对于维护安全且经济高效的云环境至关重要。安全组是 aws 网络安全的重要组成部分,但随着时间的推移,未使用的安全组会不断累积。这些未使用的组不仅会使您的环境变得混乱,还可能带来安全风险或不必要地增加成本。

在本文中,我们将探讨如何使用 python 和 boto3 识别 aws 环境中未使用的安全组、验证它们并确保它们不被任何其他资源引用。我们还将研究如何安全地确定是否可以删除这些组。

先决条件

要学习本教程,您需要以下内容:

aws 账户:确保您有权访问要搜索未使用的安全组的 aws 环境。
boto3 已安装:您可以通过运行以下命令来安装 boto3 python sdk:

PHP
   pip install boto3

已配置 aws 凭证:确保您使用 aws cli 或使用 iam 角色或环境变量直接在代码中配置了 aws 凭证。

代码分解

让我们看一下代码,用于识别给定 aws 区域中未使用的安全组、验证它们并检查它们是否被任何其他组引用。

第 1 步:获取所有安全组和 eni
PHP
import boto3
from botocore.exceptions import clienterror

def get_unused_security_groups(region='us-east-1'):
    """
    find security groups that are not being used by any resources.
    """
    ec2_client = boto3.client('ec2', region_name=region)

    try:
        # get all security groups
        security_groups = ec2_client.describe_security_groups()['securitygroups']

        # get all network interfaces
        enis = ec2_client.describe_network_interfaces()['networkinterfaces']

        # create set of security groups in use
        used_sg_ids = set()

        # check security groups attached to enis
        for eni in enis:
            for group in eni['groups']:
                used_sg_ids.add(group['groupid'])

        # find unused security groups
        unused_groups = []
        for sg in security_groups:
            if sg['groupid'] not in used_sg_ids:
                # skip default security groups as they cannot be deleted
                if sg['groupname'] != 'default':
                    unused_groups.append({
                        'groupid': sg['groupid'],
                        'groupname': sg['groupname'],
                        'description': sg['description'],
                        'vpcid': sg.get('vpcid', 'ec2-classic')
                    })

        # print results
        if unused_groups:
            print(f"
found {len(unused_groups)} unused security groups in {region}:")
            print("-" * 80)
            for group in unused_groups:
                print(f"security group id: {group['groupid']}")
                print(f"name: {group['groupname']}")
                print(f"description: {group['description']}")
                print(f"vpc id: {group['vpcid']}")
                print("-" * 80)
        else:
            print(f"
no unused security groups found in {region}")

        return unused_groups

    except clienterror as e:
        print(f"error retrieving security groups: {str(e)}")
        return none
  • 获取安全组:我们首先调用describe_security_groups方法获取指定区域内的所有安全组。
  • 检索网络接口:接下来,我们使用describe_network_interfaces检索所有网络接口。每个网络接口都可以有一个或多个与其关联的安全组。
  • 识别已使用的安全组:对于每个网络接口,我们将关联的安全组 id 添加到名为used_sg_ids 的集合中。
  • 查找未使用的组:然后我们将安全组 id 与正在使用的组 id 进行比较。如果一个组没有被使用(即它的id不在used_sg_ids集合中),我们认为它没有被使用,除了默认的安全组,它不能被删除。
步骤 2:检查安全组引用
PHP
def check_sg_references(ec2_client, group_id):
    """
    check if a security group is referenced in other security groups' rules
    """
    try:
        # check if the security group is referenced in other groups
        response = ec2_client.describe_security_groups(
            filters=[
                {
                    'name': 'ip-permission.group-id',
                    'values': [group_id]
                }
            ]
        )

        referencing_groups = response['securitygroups']

        # check for egress rules
        response = ec2_client.describe_security_groups(
            filters=[
                {
                    'name': 'egress.ip-permission.group-id',
                    'values': [group_id]
                }
            ]
        )

        referencing_groups.extend(response['securitygroups'])

        return referencing_groups

    except clienterror as e:
        print(f"error checking security group references: {str(e)}")
        return none
  • 检查引用:此函数检查特定安全组是否被任何其他安全组引用。它通过根据入站 (ip-permission.group-id) 和出站 (egress.ip-permission.group-id) 规则过滤安全组来实现此目的。
  • 返回引用组:如果引用组,则该函数返回引用安全组的列表。如果没有,则返回 none。
步骤 3:验证未使用的安全组
PHP
def validate_unused_groups(region='us-east-1'):
    """
    validate and provide detailed information about unused security groups
    """
    ec2_client = boto3.client('ec2', region_name=region)
    unused_groups = get_unused_security_groups(region)

    if not unused_groups:
        return

    print("
validating security group references...")
    print("-" * 80)

    for group in unused_groups:
        group_id = group['groupid']
        referencing_groups = check_sg_references(ec2_client, group_id)

        if referencing_groups:
            print(f"
security group {group_id} ({group['groupname']}) is referenced by:")
            for ref_group in referencing_groups:
                print(f"- {ref_group['groupid']} ({ref_group['groupname']})")
        else:
            print(f"
security group {group_id} ({group['groupname']}) is not referenced by any other groups")
            print("this security group can be safely deleted if not needed")
  • 验证未使用的安全组:在最后一步中,脚本首先检索未使用的安全组。然后,对于每个未使用的组,它会检查是否有任何其他安全组在其规则中引用它。
  • 输出:脚本输出该组是否被引用,如果没有,则可以安全删除。
运行脚本

要运行脚本,只需执行 validate_unused_groups 函数即可。例如,当区域设置为 us-east-1 时,脚本将:

  1. 检索 us-east-1 中的所有安全组和网络接口。
  2. 识别未使用的安全组。
  3. 验证并报告这些未使用的组是否被其他安全组引用。
示例输出
PHP
Found 5 unused security groups in us-east-1:
--------------------------------------------------------------------------------
Security Group ID: sg-12345678
Name: unused-sg-1
Description: Unused security group
VPC ID: vpc-abcde123
--------------------------------------------------------------------------------
Security Group sg-12345678 (unused-sg-1) is not referenced by any other groups
This security group can be safely deleted if not needed
--------------------------------------------------------------------------------
Security Group ID: sg-23456789
Name: unused-sg-2
Description: Another unused group
VPC ID: vpc-abcde123
--------------------------------------------------------------------------------
Security Group sg-23456789 (unused-sg-2) is referenced by:
- sg-34567890 (some-other-sg)
结论

使用此脚本,您可以自动执行在 aws 中查找未使用的安全组的过程,并确保您不会保留不必要的资源。这有助于减少混乱、改善安全状况,并可能通过删除未使用的资源来降低成本。

您可以将此脚本扩展为:

  • 根据标签、vpc 或其他条件处理额外的过滤。
  • 在检测到未使用的组时实施更高级的报告或警报。
  • 与 aws lambda 集成以进行自动定期检查。

确保您的 aws 环境安全且组织良好!

以上就是使用 Python 和 Boto3 查找并验证 AWS 中未使用的安全组的详细内容,更多请关注知识资源分享宝库其它相关文章!

版权声明

本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com

分享:

扫一扫在手机阅读、分享本文

发表评论
热门文章
  • BioWare埃德蒙顿工作室面临关闭危机,龙腾世纪制作总监辞职引关注(龙腾.总监.辞职.危机.面临.....)

    BioWare埃德蒙顿工作室面临关闭危机,龙腾世纪制作总监辞职引关注(龙腾.总监.辞职.危机.面临.....)
    知名变性人制作总监corrine busche离职bioware,引发业界震荡!外媒“smash jt”独家报道称,《龙腾世纪:影幢守护者》制作总监corrine busche已离开bioware,此举不仅引发了关于个人职业发展方向的讨论,更因其可能预示着bioware埃德蒙顿工作室即将关闭而备受关注。本文将深入分析busche离职的原因及其对bioware及游戏行业的影响。 Busche的告别信:挑战与感激并存 据“Smash JT”获得的内部邮件显示,Busche离职原...
  • boss直聘怎么取消面试预约 boss直聘上面试爽约了会怎么样(面试.爽约.预约.取消.boss.....)

    boss直聘怎么取消面试预约 boss直聘上面试爽约了会怎么样(面试.爽约.预约.取消.boss.....)
    求职宝典:boss直聘面试技巧及取消预约方法 各位求职者注意啦!在Boss直聘上,随意取消面试预约会留下爽约记录,影响后续求职!本文将指导您如何避免爽约,以及如何取消已预约的面试。 如何取消Boss直聘面试预约? 打开Boss直聘APP,进入“我的”页面。 点击“待面试”,查看面试日程。 选择需要取消的面试,点击“取消面试”按钮即可。 Boss直聘面试爽约的后果? 爽约行为会在HR端留下记录,影响您的求职成功率。其他HR也能看到您的不良记录,所以务必重视面试预约。...
  • 闪耀暖暖靡城永恒怎么样-闪耀暖暖靡城永恒套装介绍(闪耀.暖暖.套装.介绍.....)

    闪耀暖暖靡城永恒怎么样-闪耀暖暖靡城永恒套装介绍(闪耀.暖暖.套装.介绍.....)
    闪耀暖暖钻石竞技场第十七赛季“华梦泡影”即将开启!全新闪耀性感套装【靡城永恒】震撼来袭!想知道如何获得这套精美套装吗?快来看看吧! 【靡城永恒】套装设计理念抢先看: 设计灵感源于夜色中的孤星,象征着淡然、漠视一切的灰色瞳眸。设计师希望通过这套服装,展现出在虚幻与真实交织的夜幕下,一种独特的魅力。 服装细节考究,从面料的光泽、鞋跟声响到裙摆的弧度,都力求完美还原设计初衷。 【靡城永恒】套装设计亮点: 闪耀的绸缎与金丝交织,轻盈的羽毛增添华贵感。 这套服装仿佛是从无尽的黑...
  • 蛋仔派对2025最新皮肤兑换码汇总 最新皮肤兑换码一览(兑换.皮肤.最新.派对.汇总.....)

    蛋仔派对2025最新皮肤兑换码汇总 最新皮肤兑换码一览(兑换.皮肤.最新.派对.汇总.....)
    蛋仔派对2025最新皮肤兑换码大放送!游戏内新增多款皮肤兑换码,包含最新、福利和通用三种类型,助你轻松获取精美奖励! 赶紧来看看如何兑换吧! 兑换码列表: 最新兑换码: ccewndj4k4k、cdkqdfm4fh、peetnmp4ef、cdxymk8f67 福利兑换码: cca863ywtfa、eggy2310am、eggy2311gz、eggyeggy9wz 通用兑换码: pec74dkcty、jsrqkrrjmh、cd3wt7wrph、ccepn7d8cjf...
  • python怎么调用其他文件函数

    python怎么调用其他文件函数
    在 python 中调用其他文件中的函数,有两种方式:1. 使用 import 语句导入模块,然后调用 [模块名].[函数名]();2. 使用 from ... import 语句从模块导入特定函数,然后调用 [函数名]()。 如何在 Python 中调用其他文件中的函数 在 Python 中,您可以通过以下两种方式调用其他文件中的函数: 1. 使用 import 语句 优点:简单且易于使用。 缺点:会将整个模块导入到当前作用域中,可能会导致命名空间混乱。 步骤:...