gpt4 book ai didi

amazon-web-services - 如何列出所有公开的 AWS S3 对象?

转载 作者:行者123 更新时间:2023-12-04 16:10:41 32 4
gpt4 key购买 nike

我想列出我的 s3 存储桶中的所有公共(public)对象。使用 get-object-acl 会列出特定对象的受赠者,所以我想知道是否有更好的选择

最佳答案

依赖 get-object-acl 可能不是您想做的,因为对象可以通过其 ACL 以外的方式公开。至少,这可以通过对象的 ACL 和存储桶的策略(参见例如 https://havecamerawilltravel.com/photographer/how-allow-public-access-amazon-bucket/ )实现,也许还有其他我不知道的方法。

更聪明的测试是在没有凭据的情况下向每个对象发出 HEAD 请求。如果你得到 200,它就是公开的。如果您收到 403,则不是。

那么,步骤是:

  1. 使用 ListBuckets 获取桶列表端点。在 CLI 中,这是:

    aws2 s3api list-buckets
  2. 对于每个桶,获取其区域并列出其对象。从 CLI(假设您已配置使用它的凭据),您可以分别使用这两个命令执行这两件事:

    aws2 s3api get-bucket-location --bucket <i>bucketnamehere</i>
    aws2 s3api list-objects --bucket <i>bucketnamehere</i>
  3. 对于每个对象,向如下 URL 发出 HEAD 请求

    https://bucketname.s3.us-east-1.amazonaws.com/objectname

    with bucketname, us-east-1, and objectname 分别替换为你的bucket名称,bucket所在区域的实际名称,和你的对象名称。

    要使用 Curl 从 Unix 命令行执行此操作,请执行

    curl -I https://<i>bucketname</i>.s3.<i>us-east-1</i>.amazonaws.com/<i>objectname</i>

使用 Boto 3 和 Requests 在 Python 中实现上述逻辑的示例:

from typing import Iterator
import boto3
import requests

s3 = boto3.client('s3')
all_buckets = [
bucket_dict['Name'] for bucket_dict in
s3.list_buckets()['Buckets']
]

def list_objs(bucket: str) -> Iterator[str]:
"""
Generator yielding all object names in the bucket. Potentially requires
multiple requests for large buckets since list_objects is capped at 1000
objects returned per call.
"""
response = s3.list_objects_v2(Bucket=bucket)
while True:
if 'Contents' not in response:
# Happens if bucket is empty
return
for obj_dict in response['Contents']:
yield obj_dict['Key']
last_key = obj_dict['Key']
if response['IsTruncated']:
response = s3.list_objects_v2(Bucket=bucket, StartAfter=last_key)
else:
return

def is_public(bucket: str, region: str, obj: str) -> bool:
url = f'https://{bucket}.s3.{region}.amazonaws.com/{obj}'
resp = requests.head(url)
if resp.status_code == 200:
return True
elif resp.status_code == 403:
return False
else:
raise Exception(f'Unexpected HTTP code {resp.status_code} from {url}')

for bucket in all_buckets:
region = s3.get_bucket_location(Bucket=bucket)['LocationConstraint']
for obj in list_objs(bucket):
if is_public(bucket, region, obj):
print(f'{bucket}/{obj} is public')

请注意,每个对象这大约需要一秒钟,如果您在 S3 中有很多东西,那么这……并不理想。不过,我不知道有更快的选择。

关于amazon-web-services - 如何列出所有公开的 AWS S3 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42142091/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com