簡體   English   中英

如何檢查 S3 存儲桶中的對象在 boto3 中是否公開?

[英]How can I check if an object in an S3 bucket is public or not in boto3?

我正在嘗試使用 python 中的 boto3 模塊檢查指定存儲桶中的所有對象是否都是公共的。 我曾嘗試使用client.get_object()client.list_objects()方法,但我無法弄清楚我應該搜索什么,因為我是 boto3 和 AWS 的新手。

此外,由於我的組織更喜歡使用client不是resource ,所以我最好尋找一種使用client

可能是這些的組合來講述每個對象的完整故事

client = boto3.client('s3')
bucket = 'my-bucket'
key = 'my-key'
client.get_object_acl(Bucket=bucket, Key=key)
client.get_bucket_acl(Bucket=bucket)
client.get_bucket_policy(Bucket=bucket)

我認為測試對象是否公開的最好方法是向該對象 URL 發出匿名請求。

import boto3
import botocore
import requests

bucket_name = 'example-bucket'
object_key = 'example-key'

config = botocore.client.Config(signature_version=botocore.UNSIGNED)
object_url = boto3.client('s3', config=config).generate_presigned_url('get_object', Params={'Bucket': bucket_name, 'Key': object_key})
resp = requests.get(object_url)
if resp.status_code == 200:
    print('The object is public.')
else:
    print('Nope! The object is private or inaccessible.')

注意:您可以使用requests.head而不是requests.get來保存一些數據傳輸。

這個函數應該可以解決問題。 它獲取 ACL,然后通過Grants循環查找具有READFULL_CONTROL權限的AllUsers

import boto3

def is_public(key, bucket):
    """Returns true if key has public access.

    Args:
        key (str): key to check
        bucket (str, optional): Bucket name.

    Returns:
        (bool)

    Public object ACL example:
    {
        ...
        "Grants": [
            {
                "Grantee": {
                    "Type": "Group",
                    "URI": "http://acs.amazonaws.com/groups/global/AllUsers",
                },
                "Permission": "READ",
            },
            {
                "Grantee": {
                    "ID": "somecrypticidstring",
                    "Type": "CanonicalUser",
                },
                "Permission": "FULL_CONTROL",
            },
        ],
    }

    Private object ACL example:
    {
        ...
        "Grants": [
            {
                "Grantee": {
                    "ID": "somecrypticidstring",
                    "Type": "CanonicalUser",
                },
                "Permission": "FULL_CONTROL",
            }
        ],
    }
    """
    client = boto3.client(
        "s3",
        aws_access_key_id=YOUR_AWS_ACCESS_KEY_ID,
        aws_secret_access_key=YOUR_AWS_SECRET_ACCESS_KEY,
    )
    d = client.get_object_acl(Bucket=bucket, Key=key)

    try:
        for grant in d["Grants"]:
            if (
                "URI" in grant["Grantee"]
                and grant["Grantee"]["URI"].endswith("AllUsers")
                and grant["Permission"] in ["READ", "FULL_CONTROL"]
            ):
                return True
        return False
    except Exception:
        # Cannot determine if s3 object is public.
        return False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM