Last active
April 19, 2021 14:02
-
-
Save mdwhatcott/df9bf33cf044b7352e18 to your computer and use it in GitHub Desktop.
Generate a pre-signed S3 URL (valid for 20 years) with nothing but the standard library.
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 python | |
""" | |
Generates a pre-signed S3 URL using a valid key pair that lasts for 20 years. | |
Reference: http://forrst.com/posts/Python_method_for_creating_authenticated_s3_URLs-uUM | |
""" | |
import base64, hmac, os, sha, sys, time, urllib | |
if len(sys.argv) < 2: | |
print 'USAGE: python s3_presign.py "</bucket-name/path/to/resource"> <seconds-alive>' | |
exit(1) | |
# Declarations: | |
TWENTY_YEARS_IN_SECONDS = 60 * 60 * 24 * 365 * 20 | |
aws_access_key_id = os.environ.get('AWS_ACCESS_KEY_ID') | |
aws_secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY') | |
resource = sys.argv[1] | |
seconds_alive = TWENTY_YEARS_IN_SECONDS if len(sys.argv) < 3 else int(sys.argv[2]) | |
# Computations: | |
expires = int(time.time()) + seconds_alive | |
resource = urllib.quote(resource) | |
raw_value = "GET\n\n\n{0}\n{1}".format(expires, resource) | |
signature = base64.b64encode(hmac.new(aws_secret_access_key, raw_value, sha).digest()) | |
# Result: | |
print "https://s3.amazonaws.com{0}?AWSAccessKeyId={1}&Expires={2}&Signature={3}".format( | |
resource, urllib.quote(aws_access_key_id), expires, urllib.quote(signature)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great help, updated for newer python versions here https://gist.github.com/benjaminjbachman/99ba2de785be5a047977b4a0b4252062