Python Script to Identify IP Ranges for EC2 Instance Connect

Today I needed to identify what IP ranges need to be added in security groups that allow EC2 Instance Connect to be able to establish a connection to a node.

I absolutely did not want to open port 22 to the entire internet for obvious security reasons.

As such, I found after reading through AWS docs that they maintain a JSON list that can be periodically parsed in the event they add/remove/change any IP ranges that are associated with internal services.

As a result I wrote up a quick python script so the engineer who is tasked with this doesn’t have to parse through thousands of lines of JSON in order to find the specific criteria needed.

Just change your desired region and service at the top of the file and run it – it will output the ranges you need to add in the specified security group.

from urllib.request import urlopen
import json

desired_service = 'EC2_INSTANCE_CONNECT'
desired_region = 'us-east-2'

url = ''
response = urlopen(url)
json_obj = json.load(response)

for ip_range in json_obj['prefixes']:
    service = ip_range['service']
    ip_prefix = ip_range['ip_prefix']
    region = ip_range['region']

    if region.strip().upper() == desired_region.strip().upper():
        if service.strip().upper() == desired_service.strip().upper():
            print('[INFO] You should allow {ip_prefix} for {service} originating from {region}'.format(ip_prefix=ip_prefix, service=service, region=region))

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s