Last active
July 28, 2019 01:09
-
-
Save phwelo/80951f4ee75ac8c1a4e111ec5d77a50f to your computer and use it in GitHub Desktop.
Search which Security groups have 0.0.0.0/0 incoming, and figure out which instances use them
This file contains hidden or 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/python3 | |
import boto3 | |
ec2_client = boto3.client('ec2') | |
def find_in_sg(ip_address): | |
sg = ec2_client.describe_security_groups() | |
security_groups = [] | |
for group in sg['SecurityGroups']: | |
for permission in group['IpPermissions']: | |
for range in permission['IpRanges']: | |
if ip_address in range['CidrIp']: | |
security_groups.append(group['GroupName']) | |
return set(security_groups) | |
def sg_instance_search(security_group): | |
response = ec2_client.describe_instances( | |
Filters=[{ | |
'Name': 'instance.group-name', | |
'Values': [ security_group ] | |
}, | |
] | |
) | |
result = [] | |
for reservation in response['Reservations']: | |
result.append(reservation['Instances']) | |
return(result) | |
def is_instance_private(instance_obj): | |
if 'PublicIpAddress' in instance_obj: | |
return False | |
else: | |
return True | |
def get_instance_name(instance_obj): | |
for pair in instance_obj['Tags']: | |
if pair['Key'] == 'Name': | |
return pair['Value'] | |
def print_heading(): | |
print('Instance ID Security Group Public IP Instance Name ') | |
print('------------ --------------- ---------- -------------- ') | |
def get_spaces(desired_length, input_string): | |
length = len(input_string) | |
return desired_length - length | |
def main(): | |
print_heading() | |
results = find_in_sg('0.0.0.0/0') | |
for level_1 in results: | |
instances = sg_instance_search(level_1) | |
# now to get out of the hole we've dug ourselves into with all the nested lists | |
if len(instances) > 0: | |
for list1 in instances: | |
for instance in list1: | |
if not is_instance_private(instance): | |
print( | |
instance['InstanceId'] + | |
' ' * get_spaces(20, instance['InstanceId']) + | |
level_1 + | |
' ' * get_spaces(30, level_1) + | |
instance['PublicIpAddress'] + | |
' ' * get_spaces(16, instance['PublicIpAddress']) + | |
get_instance_name(instance) | |
) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment