Skip to content

Instantly share code, notes, and snippets.

@Burekasim
Created June 28, 2022 09:13
Show Gist options
  • Save Burekasim/e2cf731b510ff9ca5d93698e12655cdd to your computer and use it in GitHub Desktop.
Save Burekasim/e2cf731b510ff9ca5d93698e12655cdd to your computer and use it in GitHub Desktop.
MFA aws cli token generation
#!/usr/local/bin/python3
import configparser
import boto3
import pyotp
import keyring
if __name__ == '__main__':
try:
# mfa-secret - the name of secret in MacOS keychain access
mfa_token_secret = keyring.get_password("mfa-secret", "mfa-secret")
# mfa_serial - MFA ARN in AWS IAM user
mfa_serial = 'arn:aws:iam::01234567890:mfa/iam-user-name'
# user_profile - the iam user profile in ~/.aws/credentials
session = boto3.session.Session(profile_name='user_profile')
sts = session.client('sts')
mfa_token_digits = pyotp.TOTP(mfa_token_secret).now()
response = sts.get_session_token(DurationSeconds=43200, SerialNumber=mfa_serial, TokenCode=mfa_token_digits)
config = configparser.ConfigParser()
# user - replace user with your MacOS user
credentials_file = '/Users/user/.aws/credentials'
config.read(credentials_file)
# mfa-profile - your AWS mfa profile
config['mfa-profile'] = {'aws_access_key_id': response['Credentials']['AccessKeyId'],
'aws_secret_access_key': response['Credentials']['SecretAccessKey'],
'aws_session_token': response['Credentials']['SessionToken']}
with open(credentials_file, 'w') as data_file:
config.write(data_file)
print('temporary session was saved to credentials file')
except Exception as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment