Skip to content

Instantly share code, notes, and snippets.

@whitews
Last active December 19, 2015 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whitews/5914673 to your computer and use it in GitHub Desktop.
Save whitews/5914673 to your computer and use it in GitHub Desktop.
AWS S3 access to a private bucket - the AWS access ID user needs ListBucket privileges
import base64
import datetime, time
import sha, hmac
import email.utils
import requests
bucket_name = 'kick'
aws_access_id = "ABCDEFGHIJKLMNOPQ123"
aws_secret_access_key = "some-secret-amazon-aws-secret-access-key"
url = 'http://' + bucket_name + '.s3.amazonaws.com/'
http_verb = "GET"
content_md5 = ""
content_type = ""
date_key = "x-amz-date"
# Generate RFC 2616 formatted datetime
datetime_tuple = datetime.datetime.now().timetuple()
seconds_since_epoch = time.mktime(datetime_tuple)
rfc2616_date = email.utils.formatdate(seconds_since_epoch, usegmt=True)
canonicalized_amz_headers = ""
canonicalized_resource = "/" + bucket_name + "/"
# Build the string to sign
string_to_sign = http_verb + "\n"
string_to_sign += content_md5 + "\n"
string_to_sign += content_type + "\n"
string_to_sign += "\n" # for some reason, S3 wants an extra new line here
string_to_sign += date_key + ":" + rfc2616_date + "\n"
string_to_sign += canonicalized_amz_headers
string_to_sign += canonicalized_resource
digest = hmac.new(aws_secret_access_key, string_to_sign, sha).digest()
signature = base64.b64encode(digest)
# Construct HTTP GET request
headers = {
'User-Agent': 'python',
'Authorization': "AWS %s:%s" % (aws_access_id, signature),
'x-amz-date': rfc2616_date
}
try:
response = requests.get(url, headers=headers)
except Exception, e:
print e
print "Response Status Code: ", response.status_code
print "Response:"
print response.text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment