-
-
Save tom-knight/1b5e0dcf39062af8910e 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/python | |
''' Not my script, found on the Internet, and rediscovered on my hard drive | |
''' | |
import sys | |
def cidr_to_regex(cidr): | |
ip, prefix = cidr.split('/') | |
base = 0 | |
for val in map(int, ip.split('.')): | |
base = (base << 8) | val | |
shift = 32 - int(prefix) | |
start = base >> shift << shift | |
end = start | (1 << shift) - 1 | |
def regex(lower, upper): | |
if lower == upper: | |
return str(lower) | |
from math import log10 | |
exp = int(log10(upper - lower)) | |
if (int(str(lower)[-1]) > int(str(upper)[-1]) and exp == 0): | |
# increasing exp due to base 10 wrap to next exp" | |
exp += 1 | |
delta = 10 ** exp | |
if lower == 0 and upper == 255: | |
return "\d+" | |
if delta == 1: | |
val = "" | |
for a, b in zip(str(lower), str(upper)): | |
if a == b: | |
val += str(a) | |
elif (a, b) == ("0", "9"): | |
val += '\d' | |
elif int(b) - int(a) == 1: | |
val += '[%s%s]' % (a, b) | |
else: | |
val += '[%s-%s]' % (a, b) | |
return val | |
def gen_classes(): | |
floor_ = lambda x: int(round(x / delta, 0) * delta) | |
xs = range(floor_(upper) - delta, floor_(lower), -delta) | |
for x in map(str, xs): | |
yield '%s%s' % (x[:-exp], r'\d' * exp) | |
yield regex(lower, floor_(lower) + (delta - 1)) | |
yield regex(floor_(upper), upper) | |
return "({})".format('|'.join(gen_classes())) | |
def get_parts(): | |
for x in range(24, -1, -8): | |
yield regex(start >> x & 255, end >> x & 255) | |
return '^%s$' % r'\.'.join(get_parts()) | |
for line in sys.stdin.readlines(): | |
print cidr_to_regex( line ) | |
To make this python 2 and 3 compatible,
- add
from __future__ import division
from __future__ import print_function
before import sys
- change line 45 to:
floor_ = lambda x: int(round(x // delta, 0) * delta)
- change lines 63/64 to:
print(cidr_to_regex(line))
print()
Javascript version: https://gist.github.com/radu-c/df0408cb55de758e03b7568cc05f1865
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Previous version was failing on 74.91.16.0/20 this one should fix that