Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A script to add your ip to an ec2 security group.
#!/usr/bin/env python3
""" update_sec_group.py
Usage:
./update_sec_group.py [-v] SEC_GROUP_ID
./update_sec_group.py -a ACCESS_KEY -s SECRET_KEY [-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:
print(__doc__)
sys.exit(0)
sg_name = args[1]
# Find our public ip address.
ip = urllib.request.urlopen('https://v4.ident.me').read().decode('utf8')
cidr = ip + '/32'
# Obtain an ec2 interface.
if access_key is None:
ec2 = boto3.client('ec2', region_name='us-west-2')
else:
ec2 = boto3.client(
'ec2',
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.
try:
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))
print()
print('Success!')
except ClientError as e:
print(e)
@tylerneylon
Copy link
Author

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