Last active
February 8, 2017 23:20
-
-
Save astoeckel/3d1214f6fa5bbb46677afc2372de838d to your computer and use it in GitHub Desktop.
Hackish dhcpd.leases to hosts converter (for mdns emulation with dnsmasq)
This file contains hidden or 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 | |
import sys | |
if len(sys.argv) != 3: | |
print("Usage ./leases_to_hosts.py <DHCPD LEASES FILE> <OUTFILE>") | |
sys.exit(1) | |
def parse_string(f): | |
res = b'' | |
escaped = False | |
while True: | |
c = f.read(1) | |
if c == b'' or (c == b'"' and (not escaped)): | |
return res | |
if c == b'\\': | |
escaped = True | |
else: | |
escaped = False | |
res = res + c | |
def parse_dict(f): | |
res = [] | |
while True: | |
c = f.read(1) | |
if c == b'}' or c == b'': | |
return res | |
else: | |
f.seek(-1, 1) | |
t = parse_tuple(f) | |
if len(t) > 0: | |
res += [t] | |
def parse_tuple(f): | |
res = [] | |
s = b'' | |
in_comment = False | |
while True: | |
c = f.read(1) | |
if c == b'#': | |
in_comment = True | |
elif c == b'\n': | |
in_comment = False | |
if (c == b'' or c == b' ' or c == b'\n' or c == b'{' or c == b'"' | |
or c == b';' or c == b'}'): | |
if len(s) > 0: | |
res = res + [s] | |
s = b'' | |
if c == b'{': | |
res = res + [parse_dict(f)] | |
return res | |
elif c == b'"': | |
res = res + [parse_string(f)] | |
elif c == b';' or c == b'' or c == b'}': | |
if c == b'}': | |
f.seek(-1, 1) | |
return res | |
elif not in_comment: | |
s = s + c | |
def to_dict(arr): | |
res = {} | |
for v in arr: | |
if isinstance(v, (list, tuple)) and len(v) >= 2: | |
if len(v) == 2: | |
res[v[0]] = v[1] | |
else: | |
res[v[0]] = v[1:] | |
return res | |
with open(sys.argv[1], 'rb') as f: | |
leases = {} | |
while True: | |
t = parse_tuple(f) | |
if len(t) == 0: | |
break | |
if len(t) == 3 and t[0] == b'lease': | |
leases[t[1]] = to_dict(t[2]) | |
hosts = {} | |
for ip, info in leases.items(): | |
if b'client-hostname' in info: | |
host = info[b'client-hostname'] | |
if not host in hosts: | |
hosts[host] = ip | |
with open(sys.argv[2], 'wb') as f: | |
f.write(b'192.168.180.1 andreas-router.local\n') | |
f.write(b'192.168.180.1 andreas-router.lan\n') | |
for host, ip in hosts.items(): | |
f.write(ip) | |
f.write(b' ') | |
f.write(host) | |
f.write(b'.local\n') | |
f.write(ip) | |
f.write(b' ') | |
f.write(host) | |
f.write(b'.lan\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment