Skip to content

Instantly share code, notes, and snippets.

@EarthmanT
Created Sep 10, 2020
Embed
What would you like to do?
Create MFA Session Token and List s3 Buckets
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