Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. import boto3
  2. from botocore.exceptions import ClientError
  3.  
  4. class Auditor:
  5.  
  6. def __init__(self,accounts,regions):
  7. self.accounts = accounts
  8. self.regions = regions
  9. self.role = 'SecurityRole'
  10. self.data = {}
  11.  
  12. # Populate Instance IP Addresses in our Object data struct.
  13. def popinstanceips(self,dic,client,account,region):
  14. print("Getting Data Account= " + account + "Region=" + region)
  15. instances = client.describe_instances()
  16. instances = instances['Reservations']
  17. result = [x['Instances'][0] for x in instances if 'PublicIpAddress' in x['Instances'][0]]
  18. for item in result:
  19. dic[item['InstanceId']] = {
  20. 'ip':item['PublicIpAddress'],
  21. 'technology':'ec2',
  22. 'account':account,
  23. 'region': region
  24. }
  25.  
  26. def ec2_gather(self,account,region,tokens):
  27. client = boto3.client('ec2',
  28. region_name=region,
  29. aws_access_key_id=tokens[0],
  30. aws_secret_access_key=tokens[1],
  31. aws_session_token=tokens[2]
  32. )
  33. self.popinstanceips(self.data,client,account,region)
  34.  
  35. def assume_role(self,account,region):
  36. boto_sts = boto3.client('sts')
  37. arn ='arn:aws:iam::' + account + ':role/' + self.role
  38. try:
  39. sts_response = boto_sts.assume_role(RoleArn=arn, RoleSessionName='securitymonkey')
  40. newsession_id = sts_response["Credentials"]["AccessKeyId"]
  41. newsession_key = sts_response["Credentials"]["SecretAccessKey"]
  42. newsession_token = sts_response["Credentials"]["SessionToken"]
  43. return newsession_id,newsession_key,newsession_token
  44. except ClientError as e:
  45. print("Account= " + account + " Could not be assumed by Tool! Error: " + str(e) )
  46. return None
  47.  
  48.  
  49. def call_sts(self,data,account):
  50. # enumerate regions.
  51. for region in self.regions:
  52. tokens = self.assume_role(account,region)
  53. if tokens != None:
  54. self.ec2_gather(account,region,tokens)
  55.  
  56. def auditor(self):
  57. for account in self.accounts:
  58. self.call_sts(self.data,account)
  59. print("## Instance IP Report ##")
  60. print(self.data)
  61.  
  62. regions = ['us-west-2','us-west-1','us-east-1','us-east-2']
  63. accounts = ['accountnumber1','accountnumber2']
  64.  
  65. auditor = Auditor(accounts,regions)
  66. auditor.auditor()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement