-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsummarize.py
169 lines (125 loc) · 4.36 KB
/
summarize.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#!/usr/bin/env python
"""summarize.py - A script to parse and summarize IP addresses using
CIDR notation."""
from __future__ import print_function
__author__ = "Damian Torres"
__email__ = "[email protected]"
__version__ = "1.1"
import sys
import os
import argparse
import re
import ipaddress
# # # # # # #
# Constants #
# # # # # # #
SCRIPT_NAME = os.path.basename(__file__)
USAGE_HELP = """Usage: {} [-hV] [file]
Parse and summarize IP addresses using CIDR notation.
Optional arguments:
file input filename (default: stdin)
Other options
-h, --help display this help and exit
-V, --version output version information and exit
""".format(SCRIPT_NAME)
IPV4_VALIDATION_REGEX = re.compile("(?<!\d)(?:(?:(?:22[0-3]|2[01]\d|1[" \
+ "79][013-9]|16[0-8]|12[0-68-9]|1[013-58]\d|[2-9]\d|1?[1-9])\.(?:25[0-5" \
+ "]|2[0-4]\d|1\d{2}|[1-9]?\d))|(?:172\.(?:25[0-5]|2[0-4]\d|1\d{2}|[4-9]" \
+ "\d|3[2-9]|1[0-5]|\d))|(?:192\.(?:25[0-5]|2[0-4]\d|16[0-79]|1[0-57-9][" \
+ "0-9]|[1-9]?\d))|(?:169\.(?:25[0-35]|2[0-4]\d|1\d{2}|[1-9]?\d)))(?:\.(" \
+ "?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){2}(?!\d)(?:/(?:3[0-2]|[0-2]?\d))?")
IPV6_VALIDATION_REGEX = re.compile("(?<![0-9a-f:])(?:[0-9a-f]{1,4}(?::" \
+ "[0-9a-f]{1,4}){7}|::[0-9a-f]{1,4}(?::[0-9a-f]{1,4}){0,6}|(?:[0-9a-f]{" \
+ "1,4}:){1,7}:|[0-9a-f]{1,4}:(?::[0-9a-f]{1,4}){0,6}|(?:[0-9a-f]{1,4}:)" \
+ "{2}(?::[0-9a-f]{1,4}){1,5}|(?:[0-9a-f]{1,4}:){3}(?::[0-9a-f]{1,4}){1," \
+ "4}|(?:[0-9a-f]{1,4}:){4}(?::[0-9a-f]{1,4}){1,3}|(?:[0-9a-f]{1,4}:){5}" \
+ "(?::[0-9a-f]{1,4}){1,2}|(?:[0-9a-f]{1,4}:){6}:[0-9a-f]{1,4})(?![0-9a-" \
+ "f:])(?:/1(?:2[0-8]|[01]\d)|\d{1,2})?")
# # # # # # #
# Functions #
# # # # # # #
# Error print function
def eprint(*args, **kwargs):
print (*args, file=sys.stderr, **kwargs)
# Return version information
def version():
return """csv.py - v{version}
Written by {author} ({email})""".format(**{
"version" : __version__,
"author" : __author__,
"email" : __email__
})
# Return usage information
def usage():
return USAGE_HELP
# Handle command-line options and arguments
def optionsHandler():
parser = argparse.ArgumentParser(add_help=False,
description="Parse and lookup IP address netblocks and their " \
+ "respective owners")
parser.add_argument("-h", "--help", action="store_true",
help="display this help and exit")
parser.add_argument("-V", "--version", action="store_true",
help="output version information and exit")
parser.add_argument('filename', metavar='file', type=str, nargs="?",
help="input filename (default: stdin)")
args = parser.parse_args()
if args.version:
print(version())
exit(0)
if args.help:
print(usage())
exit(0)
return args.filename
# Parse IPv4 Addresses out of file or STDIN
def parseIPv4Networks(fn):
if not fn:
fh = sys.stdin
else:
fh = open(fn, 'r')
dictObj = {}
for line in fh:
matches = IPV4_VALIDATION_REGEX.findall(line)
for match in matches:
if sys.version_info < (3, 0):
ip = unicode(match)
else:
ip = match
ipObj = ipaddress.IPv4Network(ip)
dictObj[ipObj] = 1
myArr = list(dictObj.keys())
return myArr
# Parse IPv6 Addresses out of file or STDIN
def parseIPv6Networks(fn):
if not fn:
fh = sys.stdin
else:
fh = open(fn, 'r')
dictObj = {}
for line in fh:
matches = IPV6_VALIDATION_REGEX.findall(line)
for match in matches:
if sys.version_info < (3, 0):
ip = unicode(match)
else:
ip = match
ipObj = ipaddress.IPv6Network(ip)
dictObj[ipObj] = 1
myArr = list(dictObj.keys())
return myArr
# Main function
def main():
# Grab our options
fn = optionsHandler()
# Go parse addresses from our input file or stdin
ipv4_nets = parseIPv4Networks(fn)
ipv6_nets = parseIPv6Networks(fn)
ipv4_sum = list(ipaddress.collapse_addresses(ipv4_nets))
ipv6_sum = list(ipaddress.collapse_addresses(ipv6_nets))
for net in sorted(ipv4_sum):
print(net)
for net in sorted(ipv6_sum):
print(net)
return
if __name__ == "__main__":
main()