Last active
February 8, 2021 08:59
-
-
Save mims92/554a5d9e38e2820019c6afe3a319c6bd to your computer and use it in GitHub Desktop.
AWS - Python - Pre Sign S3 key
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
# coding: utf-8 | |
# Usage: python pre-sign.py -h | |
######################################## | |
import boto3 | |
import datetime | |
import sys, getopt | |
from botocore.client import Config | |
expiration = 93200 | |
try: | |
opts, args = getopt.getopt(sys.argv[1:],"hu:e:",["url=","exp="]) | |
except getopt.GetoptError: | |
print sys.argv[0] + ' -u s3:// [-e <expiration_seconds>]' | |
sys.exit(2) | |
for opt, arg in opts: | |
if opt == '-h': | |
print sys.argv[0] + ' -u s3:// [-e <expiration_seconds>]' | |
sys.exit() | |
elif opt in ("-u", "--url"): | |
s3_url = arg | |
elif opt in ("-e", "--exp"): | |
expiration = arg | |
session = boto3.Session(profile_name="",region_name="eu-central-1") | |
s3 = session.client('s3',region_name="eu-central-1",config=Config(signature_version='s3v4')) | |
s3_object=s3_url | |
s3_bucket=s3_object.split("/")[2] | |
s3_key="/".join(s3_object.split("/")[3:]) | |
print(" Generating pre-signed url...") | |
print(s3.generate_presigned_url('get_object', Params={'Bucket':s3_bucket,'Key':s3_key}, ExpiresIn=expiration)) | |
now = datetime.datetime.now() | |
now = now + datetime.timedelta(0, 172800) | |
print("Expires in %s" % (now)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment