Skip to content

Instantly share code, notes, and snippets.

@tolidano
Created November 30, 2018 01:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tolidano/3382c52947164e6d946e8181999cb249 to your computer and use it in GitHub Desktop.
Save tolidano/3382c52947164e6d946e8181999cb249 to your computer and use it in GitHub Desktop.
Python Gadget to add SSH from the current IP using default AWS profile to security group named SSH
import boto3
from botocore.exceptions import ClientError
import json
import requests
ec2 = boto3.client('ec2')
def get_ip():
r = requests.get('http://checkip.amazonaws.com')
return r.text.strip()
def main():
masked = '{}/32'.format(get_ip())
r = ec2.describe_security_groups(GroupNames=['SSH'])
if not len(r['SecurityGroups']):
print 'No Groups named SSH, exiting'
return
group_id = r['SecurityGroups'][0]['GroupId']
for ip in r['SecurityGroups'][0]['IpPermissions'][0]['IpRanges']:
if ip['CidrIp'] == masked:
print 'Already able to access, exiting'
return
try:
response = ec2.authorize_security_group_ingress(
CidrIp=masked,
GroupId=group_id,
FromPort=22,
ToPort=22,
IpProtocol='tcp',
)
except ClientError as e:
print e.message
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment