Boto3 列出每个aws安全组中的所有规则

1 boto3

为了获得我使用的所有组:

groups = list(ec2.security_groups.all())
Run Code Online (Sandbox Code Playgroud)

然后:

rules = []
for grp in groups:
   sgid =  grp.group_id
   try:
       response = ec2_client.describe_security_groups(GroupIds=[sgid])
       rules.append(response)
   except ClientError as e:
       print(e)
Run Code Online (Sandbox Code Playgroud)

我留下了一个令人讨厌的 json 来解析:-(。

vis*_*l.k 5

以下是获得所需输出的多种方法之一。

import boto3

ec2 = boto3.client('ec2', region_name='ap-south-1')
response = ec2.describe_security_groups()
for i in response['SecurityGroups']:
    print("Security Group Name: " + i['GroupName'])
    print("the Egress rules are as follows: ")
    for j in i['IpPermissionsEgress']:
        print("IP Protocol: " + j['IpProtocol'])
        for k in j['IpRanges']:
            print("IP Ranges: " + k['CidrIp'])
    print("The Ingress rules are as follows: ")
    for j in i['IpPermissions']:
        print("IP Protocol: " + j['IpProtocol'])
        try:
            print("PORT: " + str(j['FromPort']))
            for k in j['IpRanges']:
                print("IP Ranges: " + k['CidrIp'])
        except Exception:
            print("No value for ports and ip ranges available for this security group")
            continue
Run Code Online (Sandbox Code Playgroud)