찾다
백엔드 개발파이썬 튜토리얼Python 및 Boto3를 사용하여 AWS에서 사용되지 않는 보안 그룹 찾기 및 검증

Finding and Validating Unused Security Groups in AWS with Python and Boto3

안전하고 비용 효율적인 클라우드 환경을 유지하려면 AWS 보안 그룹을 효과적으로 관리하는 것이 중요합니다. 보안 그룹은 AWS 네트워크 보안의 중요한 부분이지만 시간이 지남에 따라 사용되지 않는 보안 그룹이 누적될 수 있습니다. 이러한 사용되지 않는 그룹은 환경을 복잡하게 만들 뿐만 아니라 보안 위험을 초래하거나 불필요하게 비용을 증가시킬 수도 있습니다.

이 기사에서는 Python 및 Boto3를 사용하여 AWS 환경에서 사용되지 않는 보안 그룹을 식별하고 검증하며 다른 리소스에서 참조되지 않는지 확인하는 방법을 살펴보겠습니다. 또한 이러한 그룹을 삭제할 수 있는지 안전하게 확인하는 방법도 살펴보겠습니다.

전제조건

이 튜토리얼을 진행하려면 다음이 필요합니다.

AWS 계정: 사용하지 않는 보안 그룹을 검색하려는 AWS 환경에 대한 액세스 권한이 있는지 확인하세요.
Boto3 설치: 다음을 실행하여 Boto3 Python SDK를 설치할 수 있습니다.

   pip install boto3

AWS 자격 증명 구성: AWS CLI를 사용하거나 IAM 역할 또는 환경 변수를 사용하여 코드에서 직접 AWS 자격 증명을 구성했는지 확인하세요.

코드 분석

특정 AWS 리전에서 사용되지 않는 보안 그룹을 식별하고 검증하며 다른 그룹에서 참조하는지 확인하는 코드를 살펴보겠습니다.

1단계: 모든 보안 그룹 및 ENI 가져오기

   pip install boto3
  • 보안 그룹 검색: 먼저 지정된 지역의 모든 보안 그룹을 가져오기 위해 explain_security_groups 메서드를 호출합니다.
  • 네트워크 인터페이스 검색: 다음으로, explain_network_interfaces를 사용하여 모든 네트워크 인터페이스를 검색합니다. 각 네트워크 인터페이스에는 하나 이상의 보안 그룹이 연결될 수 있습니다.
  • 사용된 보안 그룹 식별: 각 네트워크 인터페이스에 대해 관련 보안 그룹 ID를 Used_sg_ids라는 집합에 추가합니다.
  • 사용하지 않는 그룹 찾기: 그런 다음 보안 그룹 ID를 사용 중인 그룹 ID와 비교합니다. 그룹이 사용 중이 아닌 경우(즉, 해당 ID가 Used_sg_ids 세트에 없음) 삭제할 수 없는 기본 보안 그룹을 제외하고는 해당 그룹이 사용되지 않은 것으로 간주됩니다.

2단계: 보안 그룹 참조 확인

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"\nFound {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"\nNo unused security groups found in {region}")

        return unused_groups

    except ClientError as e:
        print(f"Error retrieving security groups: {str(e)}")
        return None
  • 참조 확인: 특정 보안 그룹이 다른 보안 그룹에서 참조되는지 확인하는 기능입니다. 인바운드(ip-permission.group-id) 및 아웃바운드(egress.ip-permission.group-id) 규칙을 기반으로 보안 그룹을 필터링하여 이를 수행합니다.
  • 참조 그룹 반환: 그룹이 참조되면 함수는 참조 보안 그룹 목록을 반환합니다. 그렇지 않은 경우 None을 반환합니다.

3단계: 사용되지 않는 보안 그룹 검증

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
  • 사용되지 않는 보안 그룹 유효성 검사: 이 마지막 단계에서 스크립트는 먼저 사용되지 않는 보안 그룹을 검색합니다. 그런 다음 사용되지 않는 각 그룹에 대해 다른 보안 그룹이 규칙에서 이를 참조하는지 확인합니다.
  • 출력: 그룹이 참조되는지 여부를 스크립트에서 출력하고, 참조되지 않으면 안전하게 삭제할 수 있습니다.

스크립트 실행

스크립트를 실행하려면 단순히 verify_unused_groups 함수를 실행하면 됩니다. 예를 들어 지역이 us-east-1로 설정된 경우 스크립트는 다음을 수행합니다.

  1. us-east-1의 모든 보안 그룹 및 네트워크 인터페이스를 검색합니다.
  2. 사용하지 않는 보안 그룹을 식별하세요.
  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("\nValidating 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"\nSecurity 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"\nSecurity Group {group_id} ({group['GroupName']}) is not referenced by any other groups")
            print("This security group can be safely deleted if not needed")

결론

이 스크립트를 사용하면 AWS에서 사용되지 않는 보안 그룹을 찾는 프로세스를 자동화하고 불필요한 리소스를 유지하지 않도록 할 수 있습니다. 이를 통해 혼란을 줄이고 보안 상태를 개선하며 사용하지 않는 리소스를 제거하여 잠재적으로 비용을 절감할 수 있습니다.

이 스크립트를 다음으로 확장할 수 있습니다.

  • 태그, VPC 또는 기타 기준에 따라 추가 필터링을 처리합니다.
  • 사용하지 않는 그룹이 감지되면 더욱 고급 보고 또는 경고를 구현합니다.
  • 자동화된 예약 확인을 위해 AWS Lambda와 통합하세요.

AWS 환경을 안전하고 체계적으로 유지하세요!

위 내용은 Python 및 Boto3를 사용하여 AWS에서 사용되지 않는 보안 그룹 찾기 및 검증의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
파이썬 : 편집과 해석에 대한 깊은 다이빙파이썬 : 편집과 해석에 대한 깊은 다이빙May 12, 2025 am 12:14 AM

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?May 12, 2025 am 12:09 AM

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

루프 대 파이썬의 루프 : 주요 차이점 설명루프 대 파이썬의 루프 : 주요 차이점 설명May 12, 2025 am 12:08 AM

forloopsareideal when

루프를위한 것 및 기간 : 실용 가이드루프를위한 것 및 기간 : 실용 가이드May 12, 2025 am 12:07 AM

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

파이썬 : 진정으로 해석 되었습니까? 신화를 파악합니다파이썬 : 진정으로 해석 되었습니까? 신화를 파악합니다May 12, 2025 am 12:05 AM

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

동일한 요소를 가진 Python Concatenate 목록동일한 요소를 가진 Python Concatenate 목록May 11, 2025 am 12:08 AM

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

해석 대 컴파일 언어 : Python 's Place해석 대 컴파일 언어 : Python 's PlaceMay 11, 2025 am 12:07 AM

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

루프를 위해 및 while 루프 : 파이썬에서 언제 각각을 사용합니까?루프를 위해 및 while 루프 : 파이썬에서 언제 각각을 사용합니까?May 11, 2025 am 12:05 AM

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음