Skip to content

Instantly share code, notes, and snippets.

@rcj4747
Last active October 16, 2018 07:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rcj4747/13cc8cfa9acf1c4c2c03fb73f4167e1f to your computer and use it in GitHub Desktop.
Save rcj4747/13cc8cfa9acf1c4c2c03fb73f4167e1f to your computer and use it in GitHub Desktop.
Generate a presigned URL to download an S3 object
#!/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