Skip to content

Commit f2d6a2f

Browse files
Merge pull request #5 from meshuga/profile
Added profile support
2 parents b65f43b + 41ab7d4 commit f2d6a2f

File tree

9 files changed

+127
-127
lines changed

9 files changed

+127
-127
lines changed

aws-network-discovery.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,25 +35,31 @@
3535

3636
from commands.vpc import Vpc
3737

38-
__version__ = "0.2.1"
38+
__version__ = "0.3.0"
3939

4040
def show_options(args="sys.argv[1:]"):
4141
parser = argparse.ArgumentParser()
4242
parser.add_argument(
43-
"-v",
44-
"--vpc-id",
45-
required=True,
43+
"-v",
44+
"--vpc-id",
45+
required=True,
4646
help="Inform VPC to analyze"
4747
)
4848
parser.add_argument(
49-
"-r",
50-
"--region-name",
51-
required=False,
49+
"-r",
50+
"--region-name",
51+
required=False,
5252
help="Inform REGION to analyze. If not informed, try to get from config file"
5353
)
54-
options = parser.parse_args()
54+
parser.add_argument(
55+
"-p",
56+
"--profile_name",
57+
required=False,
58+
help="Profile to be used"
59+
)
60+
args = parser.parse_args()
5561

56-
return options
62+
return args
5763

5864

5965
def main():
@@ -65,7 +71,7 @@ def main():
6571

6672
args = show_options(sys.argv)
6773

68-
vpc = Vpc(vpc_id=args.vpc_id, region_name=args.region_name)
74+
vpc = Vpc(vpc_id=args.vpc_id, region_name=args.region_name, profile_name=args.profile_name)
6975
vpc.run()
7076

7177

commands/vpc.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,30 @@
11
from shared.awscommands import *
22
from shared.common import *
3-
import boto3
3+
44

55
class Vpc(object):
66

7-
def __init__(self, vpc_id, region_name):
7+
def __init__(self, vpc_id, region_name, profile_name):
88
self.vpc_id = vpc_id
99
self.region_name = region_name
10+
self.profile_name = profile_name
1011

1112
def run(self):
1213

1314
""" aws profile check """
14-
access_key, secret_key, region_name = check_aws_profile()
15+
session = generate_session(self.profile_name)
16+
session.get_credentials()
17+
region_name = session.region_name
1518

1619
if self.region_name is None and region_name is None:
1720
exit_critical("Neither region parameter or region config were informed")
18-
21+
1922
""" assuming region parameter precedes region configuration """
2023
if self.region_name is not None:
2124
region_name = self.region_name
22-
25+
2326
""" init class awscommands """
24-
awscommands = AwsCommands(vpc_id=self.vpc_id, region_name=region_name)
27+
awscommands = AwsCommands(VpcOptions(session=session, vpc_id=self.vpc_id, region_name=region_name))
2528
awscommands.run()
2629

2730

shared/awscommands.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,22 @@
1-
import boto3
2-
from shared.common import *
1+
from shared.common import *
32
from shared.internal.security import IAM, IAMPOLICY
43
from shared.internal.network import VPC
54
from shared.internal.compute import LAMBDA, EC2
65
from shared.internal.database import RDS, ELASTICACHE
76
from shared.internal.storage import EFS
87

8+
99
class AwsCommands(object):
1010

11-
def __init__(self, vpc_id, region_name):
12-
self.vpc_id = vpc_id
13-
self.region_name = region_name
11+
def __init__(self, vpc_options: VpcOptions):
12+
self.vpc_options = vpc_options
1413

1514
def run(self):
16-
IAM(self.vpc_id, self.region_name).run()
17-
VPC(self.vpc_id, self.region_name).run()
18-
LAMBDA(self.vpc_id, self.region_name).run()
19-
EC2(self.vpc_id, self.region_name).run()
20-
RDS(self.vpc_id, self.region_name).run()
21-
EFS(self.vpc_id, self.region_name).run()
22-
ELASTICACHE(self.vpc_id, self.region_name).run()
23-
IAMPOLICY(self.vpc_id, self.region_name).run()
15+
IAM(self.vpc_options).run()
16+
VPC(self.vpc_options).run()
17+
LAMBDA(self.vpc_options).run()
18+
EC2(self.vpc_options).run()
19+
RDS(self.vpc_options).run()
20+
EFS(self.vpc_options).run()
21+
ELASTICACHE(self.vpc_options).run()
22+
IAMPOLICY(self.vpc_options).run()

shared/common.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
import boto3
1+
from typing import NamedTuple
22
import datetime
3+
import boto3
34

4-
class bcolors:
55

6+
class bcolors:
67
colors = {'HEADER': '\033[95m',
78
'OKBLUE': '\033[94m',
89
'OKGREEN': '\033[92m',
@@ -12,24 +13,30 @@ class bcolors:
1213
'BOLD': '\033[1m',
1314
'UNDERLINE': '\033[4m'}
1415

15-
def check_aws_profile():
1616

17+
class VpcOptions(NamedTuple):
18+
session: boto3.Session
19+
vpc_id: str
20+
region_name: str
21+
22+
23+
def generate_session(profile_name):
1724
try:
18-
session = boto3.Session()
19-
credentials = session.get_credentials()
20-
credentials = credentials.get_frozen_credentials()
21-
return credentials.access_key, credentials.secret_key, session.region_name
25+
return boto3.Session(profile_name=profile_name)
2226
except Exception as e:
2327
message = "You must configure awscli before use this script.\nError: {0}".format(str(e))
2428
exit_critical(message)
2529

30+
2631
def exit_critical(message):
2732
print(bcolors.colors.get('FAIL'), message, bcolors.colors.get('ENDC'), sep="")
2833
raise SystemExit
2934

35+
3036
def message_handler(message, position):
3137
print(bcolors.colors.get(position), message, bcolors.colors.get('ENDC'), sep="")
3238

39+
3340
def datetime_to_string(o):
3441
if isinstance(o, datetime.datetime):
35-
return o.__str__()
42+
return o.__str__()

shared/internal/compute.py

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,70 @@
1-
import boto3
2-
from shared.common import *
1+
from shared.common import *
2+
33

44
class LAMBDA(object):
55

6-
def __init__(self, vpc_id, region_name):
7-
self.vpc_id = vpc_id
8-
self.region_name = region_name
9-
6+
def __init__(self, vpc_options: VpcOptions):
7+
self.vpc_options = vpc_options
8+
109
def run(self):
1110
try:
12-
client = boto3.client('lambda',region_name=self.region_name)
11+
client = self.vpc_options.session.client('lambda', region_name=self.vpc_options.region_name)
1312

1413
response = client.list_functions()
1514

1615
message_handler("\nChecking LAMBDA FUNCTIONS...", "HEADER")
1716

18-
if (len(response["Functions"]) == 0):
19-
message_handler("Found 0 Lambda Functions in region {0}".format(self.region_name), "OKBLUE")
17+
if len(response["Functions"]) == 0:
18+
message_handler("Found 0 Lambda Functions in region {0}".format(self.vpc_options.region_name), "OKBLUE")
2019
else:
2120
found = 0
2221
message = ""
2322
for data in response["Functions"]:
24-
if (data['VpcConfig']['VpcId'] == self.vpc_id):
23+
if 'VpcConfig' in data and data['VpcConfig']['VpcId'] == self.vpc_options.vpc_id:
2524
found += 1
2625
message = message + "\nFunctionName: {0} - Runtime: {1} - VpcId {2} - SubnetIds: {3}".format(
2726
data["FunctionName"],
2827
data["Runtime"],
2928
data['VpcConfig']['VpcId'],
3029
", ".join(data['VpcConfig']['SubnetIds'])
3130
)
32-
message_handler("Found {0} Lambda Functions using VPC {1} {2}".format(str(found), self.vpc_id, message),'OKBLUE')
33-
34-
31+
message_handler("Found {0} Lambda Functions using VPC {1} {2}".format(str(found), self.vpc_options.vpc_id, message),'OKBLUE')
3532
except Exception as e:
3633
message = "Can't list Lambda Functions\nError {0}".format(str(e))
3734
exit_critical(message)
3835

36+
3937
class EC2(object):
4038

41-
def __init__(self, vpc_id, region_name):
42-
self.vpc_id = vpc_id
43-
self.region_name = region_name
44-
39+
def __init__(self, vpc_options: VpcOptions):
40+
self.vpc_options = vpc_options
41+
4542
def run(self):
4643
try:
4744

48-
client = boto3.client('ec2',region_name=self.region_name)
45+
client = self.vpc_options.session.client('ec2', region_name=self.vpc_options.region_name)
4946

5047
response = client.describe_instances()
5148

5249
message_handler("\nChecking EC2 Instances...", "HEADER")
5350

54-
if (len(response["Reservations"]) == 0):
55-
message_handler("Found 0 EC2 Instances in region {0}".format(self.region_name), "OKBLUE")
51+
if len(response["Reservations"]) == 0:
52+
message_handler("Found 0 EC2 Instances in region {0}".format(self.vpc_options.region_name), "OKBLUE")
5653
else:
5754
found = 0
5855
message = ""
5956
for data in response["Reservations"]:
6057
for instances in data['Instances']:
6158
if "VpcId" in instances:
62-
if (instances['VpcId'] == self.vpc_id):
59+
if instances['VpcId'] == self.vpc_options.vpc_id:
6360
found += 1
6461
message = message + "\nInstanceId: {0} - PrivateIpAddress: {1} - VpcId {2} - SubnetIds: {3}".format(
6562
instances["InstanceId"],
6663
instances["PrivateIpAddress"],
6764
instances['VpcId'],
6865
instances['SubnetId']
6966
)
70-
message_handler("Found {0} EC2 Instances using VPC {1} {2}".format(str(found), self.vpc_id, message),'OKBLUE')
71-
67+
message_handler("Found {0} EC2 Instances using VPC {1} {2}".format(str(found), self.vpc_options.vpc_id, message),'OKBLUE')
7268
except Exception as e:
7369
message = "Can't list EC2 Instances\nError {0}".format(str(e))
7470
exit_critical(message)

shared/internal/database.py

Lines changed: 19 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,54 @@
1-
import boto3
2-
from shared.common import *
1+
from shared.common import *
2+
33

44
class RDS(object):
55

6-
def __init__(self, vpc_id, region_name):
7-
self.vpc_id = vpc_id
8-
self.region_name = region_name
9-
6+
def __init__(self, vpc_options: VpcOptions):
7+
self.vpc_options = vpc_options
8+
109
def run(self):
1110
try:
12-
client = boto3.client('rds', region_name=self.region_name)
11+
client = self.vpc_options.session.client('rds', region_name=self.vpc_options.region_name)
1312

1413
response = client.describe_db_instances()
1514

1615
message_handler("\nChecking RDS INSTANCES...", "HEADER")
1716

18-
if (len(response["DBInstances"]) == 0):
19-
message_handler("Found 0 RDS Instances in region {0}".format(self.region_name), "OKBLUE")
17+
if len(response["DBInstances"]) == 0:
18+
message_handler("Found 0 RDS Instances in region {0}".format(self.vpc_options.region_name), "OKBLUE")
2019
else:
2120
found = 0
2221
message = ""
2322
for data in response["DBInstances"]:
24-
if (data['DBSubnetGroup']['VpcId'] == self.vpc_id):
23+
if data['DBSubnetGroup']['VpcId'] == self.vpc_options.vpc_id:
2524
found += 1
2625
message = message + "\nDBInstanceIdentifier: {0} - Engine: {1} - VpcId {2}".format(
2726
data["DBInstanceIdentifier"],
2827
data["Engine"],
2928
data['DBSubnetGroup']['VpcId']
3029
)
31-
message_handler("Found {0} RDS Instances using VPC {1} {2}".format(str(found), self.vpc_id, message),'OKBLUE')
32-
33-
30+
message_handler("Found {0} RDS Instances using VPC {1} {2}".format(str(found), self.vpc_options.vpc_id, message),'OKBLUE')
3431
except Exception as e:
3532
message = "Can't list RDS Instances\nError {0}".format(str(e))
3633
exit_critical(message)
3734

35+
3836
class ELASTICACHE(object):
3937

40-
def __init__(self, vpc_id, region_name):
41-
self.vpc_id = vpc_id
42-
self.region_name = region_name
43-
38+
def __init__(self, vpc_options: VpcOptions):
39+
self.vpc_options = vpc_options
40+
4441
def run(self):
4542
try:
46-
client = boto3.client('elasticache', region_name=self.region_name)
43+
client = self.vpc_options.session.client('elasticache', region_name=self.vpc_options.region_name)
4744

4845
""" get all cache clusters """
4946
response = client.describe_cache_clusters()
5047

5148
message_handler("\nChecking ELASTICACHE CLUSTERS...", "HEADER")
5249

53-
if (len(response['CacheClusters']) == 0):
54-
message_handler("Found 0 Elasticache Clusters in region {0}".format(self.region_name), "OKBLUE")
50+
if len(response['CacheClusters']) == 0:
51+
message_handler("Found 0 Elasticache Clusters in region {0}".format(self.vpc_options.region_name), "OKBLUE")
5552
else:
5653
found = 0
5754
message = ""
@@ -61,17 +58,15 @@ def run(self):
6158

6259
cachesubnet = client.describe_cache_subnet_groups(CacheSubnetGroupName=data['CacheSubnetGroupName'])
6360

64-
if (cachesubnet['CacheSubnetGroups'][0]['VpcId'] == self.vpc_id):
61+
if cachesubnet['CacheSubnetGroups'][0]['VpcId'] == self.vpc_options.vpc_id:
6562
found += 1
6663
message = message + "\nCacheClusterId: {0} - CacheSubnetGroupName: {1} - Engine: {2} - VpcId: {3}".format(
6764
data["CacheClusterId"],
6865
data["CacheSubnetGroupName"],
6966
data["Engine"],
7067
cachesubnet['CacheSubnetGroups'][0]['VpcId']
7168
)
72-
message_handler("Found {0} Elasticache Clusters using VPC {1} {2}".format(str(found), self.vpc_id, message),'OKBLUE')
73-
74-
69+
message_handler("Found {0} Elasticache Clusters using VPC {1} {2}".format(str(found), self.vpc_options.vpc_id, message),'OKBLUE')
7570
except Exception as e:
7671
message = "Can't list Elasticache Clusters\nError {0}".format(str(e))
7772
exit_critical(message)

shared/internal/network.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
1-
import boto3
2-
from shared.common import *
1+
from shared.common import *
2+
33

44
class VPC(object):
55

6-
def __init__(self, vpc_id, region_name):
7-
self.vpc_id = vpc_id
8-
self.region_name = region_name
9-
6+
def __init__(self, vpc_options: VpcOptions):
7+
self.vpc_options = vpc_options
8+
109
def run(self):
1110
try:
12-
client = boto3.client('ec2', region_name=self.region_name)
11+
client = self.vpc_options.session.client('ec2', region_name=self.vpc_options.region_name)
1312
response = client.describe_vpcs(
14-
VpcIds=[self.vpc_id]
13+
VpcIds=[self.vpc_options.vpc_id]
1514
)
1615

1716
dataresponse = response['Vpcs'][0]
18-
message = "VPC: {0}\nCIDR Block: {1}\nTenancy: {2}".format(self.vpc_id,
17+
message = "VPC: {0}\nCIDR Block: {1}\nTenancy: {2}".format(self.vpc_options.vpc_id,
1918
dataresponse['CidrBlock'],
2019
dataresponse['InstanceTenancy'])
2120
print(message)
2221
except Exception as e:
23-
message = "There is no VpcID \"{0}\" in region {1}.\nError {2}".format(self.vpc_id, self.region_name, str(e))
22+
message = "There is no VpcID \"{0}\" in region {1}.\nError {2}".format(self.vpc_options.vpc_id, self.vpc_options.region_name, str(e))
2423
exit_critical(message)

0 commit comments

Comments
 (0)