Created
March 12, 2018 14:45
-
-
Save aaronmelton/c88188799b1eb34beca1ee8fdc1ff9b5 to your computer and use it in GitHub Desktop.
Python script to improve two-factor authentication for AWS CLI.
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
#!/usr/bin/env python | |
# | |
# aws-set-mfa.py | |
# Copyright (C) 2017-2018 Aaron Melton <aaron(at)aaronmelton(dot)com> | |
# | |
# This program is free software; you can redistribute it and/or | |
# modify it under the terms of the GNU General Public License | |
# as published by the Free Software Foundation; either version 2 | |
# of the License, or (at your option) any later version. | |
# | |
# This program is distributed in the hope that it will be useful, | |
# but WITHOUT ANY WARRANTY; without even the implied warranty of | |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
# GNU General Public License for more details. | |
# | |
# You should have received a copy of the GNU General Public License | |
# along with this program; if not, write to the Free Software | |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | |
import argparse # Required to read arguments from the command line | |
import datetime # Required for date format | |
import json # Required to read AWS STS output | |
import os # Required to determine OS of host | |
from argparse import ArgumentParser, RawDescriptionHelpFormatter | |
from datetime import datetime | |
from os import system | |
parser = ArgumentParser() | |
parser.add_argument("-t", "--token", dest="token", help="Your AWS MFA Token", default="settings.cfg", required=True) | |
parser.add_argument("-d", "--duration", dest="duration", help="Duration your credentails will be valid in seconds (900-129600)", default="43200", required=True) | |
args = parser.parse_args() | |
mfaDuration = args.duration | |
mfaToken = args.token | |
# Make sure to set your AWS IAM creds | |
os.system("aws sts get-session-token --duration-seconds "+mfaDuration+" --serial arn:aws:iam::XXXXXXXXXXXX:mfa/user.name --token-code "+mfaToken+" > /home/user/.aws/mfa.json") | |
jsonFile='/home/user/.aws/mfa.json' | |
jsonData=open(jsonFile) | |
#data = json.load(jsonData) | |
data = json.load(jsonData) | |
jsonData.close() | |
print "Copy and paste Environment Variables below:" | |
print "export AWS_ACCESS_KEY_ID="+data["Credentials"]["AccessKeyId"] | |
print "export AWS_SECRET_ACCESS_KEY="+data["Credentials"]["SecretAccessKey"] | |
print "export AWS_SESSION_TOKEN="+data["Credentials"]["SessionToken"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment