Guest User

Untitled

a guest
Jan 22nd, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import os
  3. import json
  4. import argparse
  5. import subprocess
  6. import configparser
  7. import tty
  8. from shutil import copy2
  9. import time
  10. import sys
  11.  
  12. import termios
  13.  
  14.  
  15. def readchar():
  16. fd = sys.stdin.fileno()
  17. old_settings = termios.tcgetattr(fd)
  18. try:
  19. tty.setraw(sys.stdin.fileno())
  20. ch = sys.stdin.read(1)
  21. finally:
  22. termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
  23. return ch
  24.  
  25.  
  26. parser = argparse.ArgumentParser(description='Update your AWS CLI Token')
  27. parser.add_argument('--credential-path', help='path to the aws credentials file',
  28. default=os.path.expanduser('~/.aws/credentials'))
  29.  
  30. args = parser.parse_args()
  31.  
  32. config = configparser.ConfigParser()
  33. config.read(args.credential_path)
  34.  
  35. sections = config.sections()
  36. i = 1
  37. print("Select a profile to generate token using mfa:")
  38. for section in sections:
  39. print(f"{i}. {section}")
  40. i = i + 1
  41. selection = readchar()
  42. try:
  43. profile = sections[int(selection) - 1]
  44. except ValueError:
  45. print("Invalid input")
  46. exit(0)
  47.  
  48. profile_out = profile + '-mfa'
  49.  
  50. if profile_out in config.sections():
  51. if 'aws_arn_mfa' not in config[profile_out]:
  52. config[profile_out]['aws_arn_mfa'] = input("Enter mfa arn: ")
  53. else:
  54. config.add_section(profile_out)
  55. config[profile_out]['aws_arn_mfa'] = input("Enter mfa arn: ")
  56.  
  57. token = input("Enter MFA token:")
  58. result = subprocess.run(
  59. ['aws', 'sts', 'get-session-token', '--profile', profile, '--serial-number', config[profile_out]['aws_arn_mfa'],
  60. '--token-code', token], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  61. if result.returncode != 0:
  62. parser.error(result.stderr.decode('utf-8').strip('\n'))
  63.  
  64. credentials = json.loads(result.stdout.decode('utf-8'))['Credentials']
  65.  
  66. config[profile_out]['aws_access_key_id'] = credentials['AccessKeyId']
  67. config[profile_out]['aws_secret_access_key'] = credentials['SecretAccessKey']
  68. config[profile_out]['aws_session_token'] = credentials['SessionToken']
  69.  
  70. print("Set as default\n Setting config as default will overwrite current default profile! \n Set as default (y/n)?")
  71.  
  72. if readchar() == 'y':
  73. profile_out = 'default'
  74. config[profile_out]['aws_arn_mfa'] = input("Enter mfa arn: ")
  75. config[profile_out]['aws_access_key_id'] = credentials['AccessKeyId']
  76. config[profile_out]['aws_secret_access_key'] = credentials['SecretAccessKey']
  77. config[profile_out]['aws_session_token'] = credentials['SessionToken']
  78.  
  79. copy2(args.credential_path, args.credential_path.rstrip('/') + str(time.time()) + '_bak')
  80.  
  81. with open(args.credential_path, 'w') as configFile:
  82. config.write(configFile)
  83.  
  84. print('Saved {} credentials to {}'.format(profile_out, args.credential_path))
Add Comment
Please, Sign In to add comment