Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A script to add your ip to an ec2 security group.
#!/usr/bin/env python3
./ [-v] SEC_GROUP_ID
The -v option provides more verbose output.
Adds the public ip of this machine to the given security group.
In order to use this for yourself:
* boto needs your AWS credentials. You can provide them directly
with the -a and -s command-line parameters, or boto can find
them in the file ~/.aws/credentials
* Be sure that the region name below is correct for you.
* Be sure that the ports you need are opened up below.
# ______________________________________________________________________
# Imports
import json
import sys
import urllib.request
import boto3
from botocore.exceptions import ClientError
# ______________________________________________________________________
# Main
if __name__ == '__main__':
access_key, secret_key = None, None
is_verbose = False
args = sys.argv
for i in range(len(args) - 1, 0, -1):
if args[i] == '-v':
is_verbose = True
del args[i]
if args[i] == '-a':
access_key = args[i + 1]
del args[i + 1], args[i]
if args[i] == '-s':
secret_key = args[i + 1]
del args[i + 1], args[i]
if len(args) < 2:
sg_name = args[1]
# Find our public ip address.
ip = urllib.request.urlopen('').read().decode('utf8')
cidr = ip + '/32'
# Obtain an ec2 interface.
if access_key is None:
ec2 = boto3.client('ec2', region_name='us-west-2')
ec2 = boto3.client(
aws_access_key_id = access_key,
aws_secret_access_key = secret_key,
region_name = 'us-west-2'
# Add our ipv4 address to what is allowed.
data = ec2.authorize_security_group_ingress(
GroupId = sg_name,
IpPermissions = [
{'IpProtocol': 'tcp',
'FromPort': 8888,
'ToPort': 8900,
'IpRanges': [{'CidrIp': cidr}]},
{'IpProtocol': 'tcp',
'FromPort': 22,
'ToPort': 22,
'IpRanges': [{'CidrIp': cidr}]}
if is_verbose:
print('Received successful response:')
print(json.dumps(data, indent=4))
except ClientError as e:
Copy link

tylerneylon commented Jul 15, 2022

I created this script because I avoid allowing open ports on my ec2 instances, and this makes it easier for me to allow my laptop to ssh in, or to use Jupyter, whenever I'm working from a new ip address.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment