Skip to content

如何使用 AWS SDK for Python 生成安全的 Amazon S3 PUT 预签名 URL?

2 分钟阅读
内容级别:中级
0

本指南介绍如何使用 Python 生成 Amazon S3 PUT 预签名 URL。预签名 URL 允许临时安全地将文件上传到 S3 存储桶,而无需最终用户提供 AWS 凭证。以下步骤概述了先决条件、脚本创建和使用说明。


先决条件

  • 已安装 Python 3.x
  • ~/.aws/credentials 中配置了 AWS 凭证
  1. 安装 Python 3 和所需包:

    sudo yum install python3 -y
  2. 配置 AWS 凭证:

    • 确保在 ~/.aws/credentials 中配置了凭证
    • 遵循 AWS 认证最佳实践

步骤 1:创建 Python 脚本

以下 Python 代码仅用于生成 PUT 预签名 URL。(参考 SDK 代码,移除上传文件的代码)

创建和配置脚本:

vim put-only-url.py
chmod +x put-only-url.py

Python 代码:

import argparse
import boto3
from botocore.exceptions import ClientError

def generate_presigned_url(s3_client, client_method, method_parameters, expires_in):
    """
    Generate a presigned Amazon S3 URL that can be used to perform an action.
    
    :param s3_client: A Boto3 Amazon S3 client.
    :param client_method: The name of the client method that the URL performs.
    :param method_parameters: The parameters of the specified client method.
    :param expires_in: The number of seconds the presigned URL is valid for.
    :return: The presigned URL.
    """
    try:
        url = s3_client.generate_presigned_url(
            ClientMethod=client_method,
            Params=method_parameters,
            ExpiresIn=expires_in
        )
    except ClientError:
        print(f"Couldn't get a presigned URL for client method '{client_method}'.")
        raise
    return url

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("bucket", help="The name of the bucket.")
    parser.add_argument("key", help="The key (path and filename) in the S3 bucket.")
    args = parser.parse_args()
    
    # By default, this will use credentials from ~/.aws/credentials
    s3_client = boto3.client("s3")
    
    # The presigned URL is specified to expire in 1000 seconds
    url = generate_presigned_url(
        s3_client, 
        "put_object", 
        {"Bucket": args.bucket, "Key": args.key}, 
        1000
    )
    print(f"Generated PUT presigned URL: {url}")

if __name__ == "__main__":
    main()

步骤 2:生成预签名 URL

使用你的存储桶名称和对象键运行脚本:

python put-only-url.py <bucket-name> <object-key>

示例:

python put-only-url.py 1yth-s3doc-test 20.JPG

脚本将输出一个有效期为 1000 秒的预签名 URL。例如:

[ec2-user@ip-10-0-0-238 s3doc]$ python put-only-url.py 1yth-s3doc-test 20.JPG
Generated PUT presigned URL: https://1yth-s3doc-test.s3.amazonaws.com/20.JPG?AWSAccessKeyId=AKIAT2GQOK7BBFHAWKBA&Signature=YhEzOUMXrzzxVC%2Fh0NTG%2FHdCot0%3D&Expires=1743959065

步骤 3:使用预签名 URL

使用 curl 命令通过生成的 URL 上传文件:

curl -X PUT -T "path/to/your/local/file" "generated-presigned-url"

示例:

curl -X PUT -T "/home/user/s3doc/20.JPG" "https://1yth-s3doc-test.s3.amazonaws.com/20.JPG?AWSAccessKeyId=AKIAT2GQOK7BBFHAWKBA&Signature=YhEzOUMXrzzxVC%2Fh0NTG%2FHdCot0%3D&Expires=1743959065"

重要说明:

  1. 预签名 URL 在指定时间(本例中为 1000 秒)后将失效
  2. 上传命令中的文件名可以与 S3 对象键不同
  3. 确保你的 AWS 凭证具有适当权限
  4. 预签名 URL 包含敏感信息,需安全处理

参考资料

  1. 使用预签名 URL 上传对象
  2. 使用 AWS SDK 为 Amazon S3 创建预签名 URL
AWS
专家
已​发布 1 个月前14 查看次数