简介:
本指南展示如何使用 Python 生成 Amazon S3 GET 预签名 URL。
这些 URL 允许用户在无需 AWS 凭证的情况下,临时且安全地从 S3 存储桶下载文件。请按照以下步骤设置并使用 Python 脚本生成 GET 预签名 URL。
前提条件
- 已安装 Python 3.x
- 在
~/.aws/credentials
中配置了 AWS 凭证
-
安装 Python 3 和所需包:
sudo yum install python3 -y
-
配置 AWS 凭证:
- 确保在
~/.aws/credentials
中设置了凭证。
- 遵循 AWS 认证最佳实践以确保安全性。
步骤 1:创建 Python 脚本
此 Python 脚本用于生成从 S3 存储桶下载文件的 GET 预签名 URL。它使用 AWS SDK 创建一个可与他人共享的临时链接。
-
创建并配置脚本:
vim get-only-url.py
chmod +x get-only-url.py
-
Python 代码:
将以下内容保存为 get-only-url.py
:
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,
"get_object", # Specifies the GET operation for downloading
{"Bucket": args.bucket, "Key": args.key},
1000
)
print(f"Generated GET presigned URL: {url}")
if __name__ == "__main__":
main()
步骤 2:生成预签名 URL
使用存储桶名称和对象键运行脚本,以生成用于下载文件的预签名 URL。
命令:
python get-only-url.py <bucket-name> <object-key>
示例:
python get-only-url.py bucket-name example-file.jpg
输出:
脚本将显示一个有效期为 1000 秒(约 16.7 分钟)的预签名 URL。例如:
Generated GET presigned URL: https://bucket-name.s3.amazonaws.com/example-file.jpg?AWSAccessKeyId=***&Signature=***&Expires=***
步骤 3:使用预签名 URL
将生成的 URL 分享给他人,他们可以使用该 URL 直接从 S3 下载文件。URL 可以通过浏览器或 curl
等工具访问。
命令(使用 curl):
curl "generated-presigned-url" -o "local-filename"
示例:
curl "https://bucket-name.s3.amazonaws.com/example-file.jpg?AWSAccessKeyId=***&Signature=***&Expires=***" -o "example-file.jpg"
或者,用户可以将 URL 粘贴到浏览器中手动下载文件。
重要说明
- 预签名 URL 在指定时间(本例中为 1000 秒)后失效。
- 确保文件存在于指定的 S3 存储桶中,并且对象键与文件位置匹配。
- 验证您的 AWS 凭证是否具有生成预签名 URL 和访问 S3 对象的权限。
- URL 包含敏感信息;请安全共享,避免在非必要情况下公开。
参考资料
- 使用预签名 URL 共享对象
- 使用 AWS SDK 创建 Amazon S3 预签名 URL