Created
July 31, 2022 09:26
-
-
Save einyx/fae3f2f744d2eedd4d97a2356416fc06 to your computer and use it in GitHub Desktop.
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
import boto3 | |
# Initiate the client | |
ec2 = boto3.resource('ec2', region_name="us-east-1") | |
ec2c = boto3.client('ec2', region_name="us-east-1") | |
# Grab the default VPC id | |
vpc_default = ec2c.describe_vpcs(Filters=[{'Name':'isDefault','Values': ['true']},]) | |
# Get information for all running instances | |
running_instances = ec2.instances.filter(Filters=[{ | |
'Name': 'instance-state-name', | |
'Values': ['running']}]) | |
for vpc in vpc_default['Vpcs']: | |
vpc_id = vpc['VpcId'] | |
# Check SGs for each running instance | |
for instance in running_instances: | |
for sg in instance.security_groups: | |
ip_protocol='tcp' | |
cidr_ip='0.0.0.0/0' | |
from_ssh_port=22 | |
to_ssh_port=22 | |
rules = ec2c.describe_security_groups(GroupIds=[sg["GroupId"]])# | |
for rule in rules['SecurityGroups']: | |
for r in rule['IpPermissions']: | |
if r['IpProtocol'] == ip_protocol: | |
if r['FromPort'] == from_ssh_port: | |
if r['ToPort'] == to_ssh_port: | |
for i in r['IpRanges']: | |
if i['CidrIp'] == cidr_ip: | |
try: | |
print (instance.id, 'Public SSH access detected, rule:' , i ) | |
#print(instance.terminate()) | |
except: | |
print ("Something went wrong here") | |
else: | |
if rule['VpcId'] == vpc_id: | |
print(instance + 'is running in the default VPC') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment