Last active
October 16, 2018 07:16
-
-
Save rcj4747/13cc8cfa9acf1c4c2c03fb73f4167e1f to your computer and use it in GitHub Desktop.
Generate a presigned URL to download an S3 object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""Generate a presigned URL to download an S3 object | |
<cmd> bucket_name key_name [expiration_days]""" | |
import sys | |
import boto3 | |
from botocore.client import Config | |
if len(sys.argv) < 3 or len(sys.argv) > 4: | |
print(__doc__) | |
quit() | |
BUCKET = sys.argv[1] # S3 bucket name | |
KEY = sys.argv[2] # S3 object key | |
# URL Expiration in days (default: 1) | |
DAYS = int(sys.argv[3]) if len(sys.argv) > 3 else 1 | |
# boto3 defaults to 'virtual' bucket addressing which does not work for | |
# the presigned URL, we need 'path' | |
# Thanks to https://github.com/boto/boto3/issues/1644#issuecomment-417550879 | |
# for this way to fix the 403 SignatureDoesNotMatch return code. | |
S3_CLIENT = boto3.client( | |
's3', | |
config=Config(signature_version='s3v4', | |
s3={'addressing_style': 'path'})) | |
URL = S3_CLIENT.generate_presigned_url( | |
ClientMethod='get_object', | |
Params={'Bucket': BUCKET, 'Key': KEY}, | |
ExpiresIn=DAYS*3600*24) | |
print(URL) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment