Last active
August 29, 2015 14:12
-
-
Save alexgottscha/24e3826b4118c0278d29 to your computer and use it in GitHub Desktop.
SSH Security Group fixer
This file contains 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
#!/usr/bin/env python | |
'''clear "ssh-temp" and create a new rule for all traffic from current IP''' | |
def get_my_public_ip(): | |
'''returns outbound (public) IP address in string format''' | |
from httplib import HTTPConnection | |
ipconn = HTTPConnection('icanhazip.com') | |
ipconn.request('GET', '/') | |
myip = ipconn.getresponse() | |
myip = myip.read() | |
ipconn.close() | |
return myip.strip() | |
def get_security_group(sg_name): | |
'''return a boto security group object from string name''' | |
from boto.ec2 import connect_to_region | |
conn = connect_to_region('us-west-2') | |
return conn.get_all_security_groups(filters={'group-name': sg_name})[0] | |
def revoke_all_rules_from_group(sg_name): | |
'''delete all rules from sg_name''' | |
group = get_security_group(sg_name) | |
for rule in group.rules: | |
for grant in rule.grants: | |
group.revoke( | |
ip_protocol=rule.ip_protocol, | |
from_port=rule.from_port, | |
to_port=rule.to_port, | |
cidr_ip = grant | |
) | |
def grant_my_ip(sg_name): | |
'''grant all traffic access to sg_name from current IP''' | |
my_ip = get_my_public_ip() | |
revoke_all_rules_from_group(sg_name) | |
group = get_security_group(sg_name) | |
group.authorize( | |
ip_protocol='-1', | |
from_port=None, | |
to_port=None, | |
cidr_ip=my_ip+'/32' | |
) | |
def main(): | |
'''clear "ssh-temp" and create a new rule for all traffic from current IP''' | |
group = 'ssh-temp' | |
revoke_all_rules_from_group(group) | |
grant_my_ip(group) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment