Skip to content

Instantly share code, notes, and snippets.

@ksaylor11
Created March 18, 2020 15:29
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 ksaylor11/f82aaaeca5227557c4e8a888925e2bd8 to your computer and use it in GitHub Desktop.
Save ksaylor11/f82aaaeca5227557c4e8a888925e2bd8 to your computer and use it in GitHub Desktop.
script to look up amazon ec2 instances and limit using ufw
from fabric import Connection
import requests
import yaml
if __name__ == "__main__":
# need to open our config file
with open('config.yaml', 'rb') as conf_file:
conf_data = conf_file.read()
config = yaml.load(conf_data, Loader=yaml.Loader)
r = requests.get("https://ip-ranges.amazonaws.com/ip-ranges.json")
responses = r.json()
ip_ranges = []
for ip in responses['prefixes']:
if ip['service'] == 'EC2':
print(ip)
ip_ranges.append(ip)
# make connection to server
with Connection(host=config['host'], user=config['username'], port=config['port'],
connect_kwargs={'look_for_keys': True}) as c:
for ip in ip_ranges:
# test command
#command = 'echo {0}'.format(ip['ip_prefix'])
# command to add ufw rule
command = "ufw limit from {0} to any comment 'limiting amazon ec2 {0}'".format(ip['ip_prefix'])
c.sudo(command=command, password=config['password'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment