-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmfa_automation.py
100 lines (90 loc) · 4.22 KB
/
mfa_automation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
## This is the abstructed mfa automation tool only script.
import re
import boto3
import botocore
import botocore.errorfactory
from botocore.config import Config
from os import path, system
from colorama import Fore, Style
## This function creates the mfa profile config in the ~/.aws/config file.
def create_mfa_profile():
file_path = path.expanduser('~/.aws/config')
with open(file_path, 'r+') as f:
lines = f.readlines() # Save all the lines in a variable.
f.seek(0) # Set the cursor at the beginning of the file.
for line in lines:
reg = re.match('\[profile mfa]', line) # Create a regex pattern and check if it exists in each line.
if not line.strip():
pass
elif not reg:
f.write(line)
else:
break
else:
region = input(Fore.LIGHTCYAN_EX + "Please enter your region for the mfa profile: " + Style.RESET_ALL)
f.write("\n")
f.write(f'[profile mfa]\nregion = {region}')
## This function checks if your mfa credential have expired.
def check_if_mfa_expired():
session = boto3.Session(profile_name='mfa')
client = session.client('sts')
client.get_caller_identity()
## This function converts CamelCase to snake_case for the output of aws mfa to match the credentials file format.
def change_case(camel_key):
reg_pattern = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_key)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', reg_pattern).lower()
## This function creates the temporary mfa credentials that will be inserted into the ~/.aws/credentials file.
def configure_mfa():
global mfa_creds
user = input(Fore.LIGHTCYAN_EX + "Enter your aws username: " + Style.RESET_ALL)
account_id = int(input(Fore.LIGHTCYAN_EX + "Enter your aws account id: " + Style.RESET_ALL))
mfa = input(Fore.LIGHTCYAN_EX + "Enter the mfa code: " + Style.RESET_ALL)
session = boto3.Session() # Please enter profile_name='<PROFILE>' if you are using profiles and not the default profile.
client = session.client('sts')
mfa_creds = client.get_session_token(
DurationSeconds = 129600,
SerialNumber = f'arn:aws:iam::{account_id}:mfa/{user}',
TokenCode = mfa
)
## This function writes the credentials generated by the first function into the credentials file.
def write_mfa_to_credentials_file():
file_path = path.expanduser('~/.aws/credentials')
with open(file_path, 'r+') as f:
lines = f.readlines() # Save all the lines in a variable.
f.seek(0) # Set the cursor at the beginning of the file.
for line in lines:
reg = re.match('\[mfa]', line) # Create a regex pattern and check if it exists in each line.
if not line.strip():
pass
elif not reg:
f.write(line)
else:
break
f.write("\n")
f.write('[mfa]\n')
del mfa_creds['ResponseMetadata']
del mfa_creds['Credentials']['Expiration'] # Delete unnecessary items in the dictionary.
for value in mfa_creds.values():
for key, value in value.items():
camel_key = key
key = f'aws_{change_case(camel_key)}'
f.write('%s = %s\n' % (key, value)) # Write the necessary items in a 'key = value' format instead of dict, after stripping the inner dict from the outer dict.
## Main script
system('cls||clear')
while True:
try:
create_mfa_profile()
check_if_mfa_expired()
print("Your mfa credentials are up to date.")
break
## In case the user doesn't have mfa credentials in the ~/.aws/credentials file.
except botocore.exceptions.NoCredentialsError:
print(Fore.LIGHTRED_EX + "\nYou don't have the mfa credentials set, please enter the credentials." + Style.RESET_ALL)
configure_mfa()
write_mfa_to_credentials_file()
except botocore.exceptions.ClientError as error:
## In case the credentials have expired.
if error.response['Error']['Code'] == 'ExpiredToken':
print(Fore.LIGHTRED_EX + "\nYour credentials have expired, please enter the credentials." + Style.RESET_ALL)
configure_mfa()
write_mfa_to_credentials_file()