Last active
January 25, 2019 18:10
-
-
Save mble/8b94b7fdd21d5525bcdde393d8084ee0 to your computer and use it in GitHub Desktop.
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 python3 | |
# NAME | |
# cidr-press - quickly validate a CIDR block without having to think about it | |
# | |
# SYNOPSIS | |
# cidr-press [--cidr-block CIDR_BLOCK] [--file FILE] | |
import argparse | |
import ipaddress | |
import sys | |
def main(): | |
parser = argparse.ArgumentParser( | |
description='Validate a CIDR block without thinking about it') | |
parser.add_argument('--cidr-block', help='CIDR block you wish to validate') | |
parser.add_argument( | |
'--file', help='File containing multiple CIDR blocks to validate') | |
args = parser.parse_args() | |
if args.cidr_block: | |
validate_cidr(args.cidr_block) | |
if args.file: | |
with open(args.file) as f: | |
for cidr in f: | |
validate_cidr(cidr.rstrip('\n')) | |
sys.exit(0) | |
def validate_cidr(cidr): | |
global exit_code | |
try: | |
ipaddress.ip_network(cidr, strict=True) | |
except ValueError: | |
print("%s is an invalid CIDR block" % (cidr)) | |
sys.exit(1) | |
network = ipaddress.ip_network(cidr, strict=True) | |
if network.is_private: | |
print("%s is an RFC1918 (private range) CIDR block" % (cidr)) | |
sys.exit(1) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment