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

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

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

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

先决条件

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

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

   pip install boto3

登录后复制

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

立即学习“Python免费学习笔记(深入)”;

代码分解

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

第 1 步:获取所有安全组和 eni

import boto3from botocore.exceptions import clienterrordef 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:检查安全组引用

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:验证未使用的安全组

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 时,脚本将:

检索 us-east-1 中的所有安全组和网络接口。识别未使用的安全组。验证并报告这些未使用的组是否被其他安全组引用。

示例输出

Found 5 unused security groups in us-east-1:--------------------------------------------------------------------------------Security Group ID: sg-12345678Name: unused-sg-1Description: Unused security groupVPC ID: vpc-abcde123--------------------------------------------------------------------------------Security Group sg-12345678 (unused-sg-1) is not referenced by any other groupsThis security group can be safely deleted if not needed--------------------------------------------------------------------------------Security Group ID: sg-23456789Name: unused-sg-2Description: Another unused groupVPC 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 中未使用的安全组的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2175518.html

(0)
上一篇 2025年2月25日 12:37:51
下一篇 2025年2月18日 04:56:09

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • 我们制作了一个 AI SWE,解决了 SWE 工作台上的问题,% 开源

    我们 composio 正在为 ai 代理构建工具基础设施。我们用户最大的要求之一是用于构建有效的自定义编码代理的工具包。因此,我们创建了 swe-kit,这是一个入门模板,其中包含用于构建 ai 编码代理的所有工具包。 这些代理可以在本地…

    2025年2月25日
    200
  • 值得关注的顶级编程语言哪些将塑造未来?

    随着 2025 年的临近,技术格局继续快速发展,推动了对迎合人工智能、云计算、Web 开发等新兴趋势的编程语言的需求。对于希望未来蓬勃发展的开发商和企业来说,保持领先地位至关重要。本文探讨了 2025 年将占据主导地位的 5 种编程语言、它…

    2025年2月25日
    200
  • 探索 Python 的 itertools 模块:释放迭代器的力量

    在 python 编程领域,迭代器在促进数据结构的高效且内存友好的迭代方面发挥着至关重要的作用。 python 中的 itertools 模块是一个功能强大的工具包,它提供了大量用于创建和操作迭代器的函数。在本文中,我们将深入研究 pyth…

    2025年2月25日 编程技术
    200
  • 代码的出现 &#- 天爪装置

    第 13 天:爪子装置(数学,数学,还有更多数学)。 解决方案链接 今天的挑战是用 python 完成的,但有所改变。做出此选择是为了:a) 测试我的 python / 了解更多 pythonb) 今天看起来像是一个非常沉重的数学难题,所以…

    2025年2月25日
    200
  • 强大的 Python 性能优化技术,可实现更快的代码

    作为一名 python 开发人员,我了解到优化代码对于创建高性能应用程序至关重要。在本文中,我将分享我用来增强 python 代码性能的七种强大技术,重点介绍提高执行速度和内存效率的实用方法。 生成器和迭代器 优化 python 代码最有效…

    2025年2月25日
    200
  • Python 数据分析简介:部分数据类型和变量

    数据类型 数据类型是指定变量可以保存的值/数据类型的分类。 它们包括: integer 或 int:整数(例如 1、43、78、100、34)。 string 或 str:用引号引起来的文本数据。根据编程语言的不同,它们可以用单引号 (&#…

    2025年2月25日
    200
  • Python 应用程序的 Dockerfile

    让我们为 python 应用程序创建一个简单的 dockerfile。此示例假设您有一个名为 app.py 的 python 脚本和一个包含应用程序依赖项的requirements.txt 文件。 打开终端。导航到要创建或编辑 docker…

    2025年2月25日
    200
  • Python终端推荐引擎

    codecademy cs 认证课程的下一步是推荐引擎。我编写了一个简单的视频游戏推荐,并返回 5 种类型之一的 5 款游戏,并允许玩家看到有关该列表中任何游戏的简介。 上一个项目专注于对我当前工作具有实际应用的东西,即贷款和储蓄股息的金融…

    2025年2月25日
    200
  • Dockerized lambda 函数中的相对 Python 导入

    相对 python 导入对于 lambda 函数来说可能很棘手。我三年前写过一篇关于此的博客。但最近,我在 dockerized lambda 函数方面遇到了同样的问题。所以,我想是时候创建一个新博客了! 您可以按照步骤操作或直接在 git…

    2025年2月25日
    200
  • 灵感墨水

    标题:利用 InspireInk 释放您的创造力:您的人工智能写作伴侣 写作有时感觉像是一次孤独的旅程,但如果你有一个同伴来引导你度过情节曲折、人物弧线和风格灵感呢?隆重推出 InspireInk,这是一款功能强大的人工智能驱动工具,专为想…

    2025年2月25日
    200

发表回复

登录后才能评论