Skip to content

Instantly share code, notes, and snippets.

@hdon
Created August 20, 2016 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hdon/35e1f76e03f9e0306a8b35a406037466 to your computer and use it in GitHub Desktop.
Save hdon/35e1f76e03f9e0306a8b35a406037466 to your computer and use it in GitHub Desktop.
IPv4 NAT string substitution
#!/usr/bin/env python
import sys, re
def s2ip(s):
a, b, c, d = map(int, s.split('.'))
return (a << 24) | (b << 16) | (c << 8) | d
def ip2s(n):
return '%d.%d.%d.%d' % (
(n >> 24)
,(n >> 16)& 255
,(n >> 8)& 255
,(n >> 0)& 255
)
def nat(s):
global srcnet, dstnet, netmask
x = s.span()
s = s.string[x[0]:x[1]]
srcaddr = s2ip(s)
if (srcaddr & netmask) != srcnet:
return s
srcbits = srcaddr & ~netmask
return ip2s(dstnet | srcbits)
if len(sys.argv) != 3:
print 'usage: %s <srcnet> <dstnet> # use cidr notation'
raise SystemExit
srcnet = sys.argv[1].split('/')
nbits = int(srcnet[1])
srcnet = s2ip(srcnet[0])
dstnet = sys.argv[2].split('/')
if nbits != int(dstnet[1]):
print 'number of bits in source and destination networks do not match'
raise SystemExit
dstnet = s2ip(dstnet[0])
netmask = ((1 << (32-nbits)) - 1) ^ 0xffffffff
for line in sys.stdin:
sys.stdout.write(re.sub(
r'\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b'
, nat
, line))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment