Created
July 15, 2019 20:48
-
-
Save detrout/04740a142a457d216d92bf1aa35fdbf4 to your computer and use it in GitHub Desktop.
Generate iptables commands to block and unblock amazon. (Unblock untested)
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/python3 | |
"""Block amazon. | |
I used https://github.com/joetek/aws-ip-ranges-json as the source of | |
Amazon IP address ranges so I wouldn't have to download them directly | |
from Amazon. | |
This depends on sudo, iptables and ip6tables being available. | |
git clone https://github.com/joetek/aws-ip-ranges-json | |
python3 block-amazon.py ip-address.json | |
python3 --unblock ip-address.json | |
""" | |
from argparse import ArgumentParser | |
import json | |
import subprocess | |
def main(cmdline=None): | |
parser = make_parser() | |
args = parser.parse_args(cmdline) | |
with open(args.filename, 'rt') as jsonfile: | |
data = json.load(jsonfile) | |
if args.unblock: | |
mode = 'D' | |
else: | |
mode = 'A' | |
cmds = [] | |
for prefix in data['prefixes']: | |
netblock = prefix['ip_prefix'] | |
cmds.append(['sudo', 'iptables', '-'+mode, 'INPUT', '-s', netblock, '-j', 'DROP']) | |
for prefix in data['ipv6_prefixes']: | |
netblock = prefix['ipv6_prefix'] | |
cmds.append(['sudo', 'ip6tables', '-'+mode, 'INPUT', '-s', netblock, '-j', 'DROP']) | |
for cmd in cmds: | |
print(' '.join(cmd)) | |
subprocess.check_call(cmd) | |
def make_parser(): | |
parser = ArgumentParser() | |
parser.add_argument('--unblock', action='store_true', default=False) | |
parser.add_argument('filename', help='json ip address file to load') | |
return parser | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment