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

时间:2018-07-17 19:07:55

标签: boto3

要获取我使用过的所有群组:

groups = list(ec2.security_groups.all())

然后:

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)

我剩下一个讨厌的json来解析:-(。

1 个答案:

答案 0 :(得分:1)

关注是获得所需输出的多种方法之一。

    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