amazon-web-services - 如何检索所有安全组 ID 并将它们保存到可迭代列表中?
问题描述
我想遍历所有安全组,并在任何端口上找到对互联网开放的规则。
# This script is for identifying security groups with rules with open to internet.
import boto3
def inspect(thing):
print("Funcs: "+str(dir(thing)))
for key in list(thing):
print(" "+key+": "+str(thing[key]))
ec2 = boto3.resource('ec2')
security_group = ec2.SecurityGroup('id')
type = inspect(security_group)
print ("type")
for i in security_group:
try:
response = client.describe_security_groups(GroupIds=[i])
print(response)
except ClientError as e:
print(e)
解决方案
您可以使用 EC2 低级客户端来获取所有安全组。describe_security_groups()返回一个字典对象作为响应。所以你只需要迭代它来评估你的安全组规则。
import boto3
client = boto3.client('ec2')
response = client.describe_security_groups()
for sg in response['SecurityGroups']:
for ingressrule in sg['IpPermissions']:
print(ingressrule.get('FromPort', -1))
print(ingressrule.get('ToPort', -1))
for iprange in ingressrule['IpRanges']:
print(iprange.get('CidrIp', -1))
您还可以使用过滤器仅列出具有广泛访问权限的入口规则:
client.describe_security_groups(Filters=[
{
"Name": "ip-permission.cidr",
"Values": ["0.0.0.0/0"]
}
])
推荐阅读
- server-sent-events - AWS APi 网关从 AWS 服务获取响应消息为“:”端点请求超时“504
- arrays - 在 C 中计算数组中超过 4 个元素的平均值时出错
- c++ - 为什么 GCC 在使用类型别名时处理不同的 const reinterpret_cast?
- sql - 为什么 SQL 认为我的列名不明确?
- python - Cartopy 无法下载 shapefile,因为证书不受信任
- html - 多个 HTML 文件的 CSS 顺序
- arrays - 如何将自定义结构添加到 C 中的数组?
- c# - 为什么启动中的连接字符串会干扰 EF Core 迁移?
- java - 我无法从服务器读取答案
- javascript - 在将文件发送到 mongo db 之前,是否需要在本地保存文件?