Created
March 18, 2020 15:29
-
-
Save ksaylor11/f82aaaeca5227557c4e8a888925e2bd8 to your computer and use it in GitHub Desktop.
script to look up amazon ec2 instances and limit using ufw
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
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