Created
September 10, 2020 13:02
-
-
Save EarthmanT/02ddc9d31133f2cefe05d4564edcc3c4 to your computer and use it in GitHub Desktop.
Create MFA Session Token and List s3 Buckets
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
import os | |
import boto3 | |
import pyotp | |
def get_mfa_session_token(long_term_aws_key, | |
longterm_aws_secret, | |
mfa_arn, | |
one_time_password, | |
token_ttl=900): | |
sts = boto3.client('sts', | |
aws_access_key_id=long_term_aws_key, | |
aws_secret_access_key=longterm_aws_secret) | |
totp = pyotp.TOTP(one_time_password) | |
return sts.get_session_token(DurationSeconds=token_ttl, | |
SerialNumber=mfa_arn, | |
TokenCode=totp.now()) | |
def get_s3_client(mfa_session): | |
return boto3.client('s3', | |
aws_access_key_id=mfa_session['Credentials']['AccessKeyId'], | |
aws_secret_access_key=mfa['Credentials']['SecretAccessKey'], | |
aws_session_token=mfa_session['Credentials']['SessionToken']) | |
if __name__ == '__main__': | |
# First, create a new user in AWS IAM. | |
# Second, create "Assigned MFA Device". | |
# Authenticate it. | |
# Then copy the ARN. | |
# Then copy a new one time password. | |
# Save the below environment variables. | |
session = get_mfa_session_token(os.environ['AWS_ACCESS_KEY_ID'], | |
os.environ['AWS_SECRET_ACCESS_KEY'], | |
os.environ['AWS_MFA_ARN'] | |
os.environ['AWS_MFA_OTP']) | |
client = get_s3_client(session) | |
response = client.list_buckets() | |
for bucket in response['Buckets']: | |
print buckets |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment