Last active
January 22, 2020 15:28
-
-
Save w4/7bc5bffbbf6fc58eb8db449c543b16cd to your computer and use it in GitHub Desktop.
Build a host file from a dhcp.leases file
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
# This is a simple little script for parsing dhcpd.leases files and | |
# returning a hosts file for them. | |
# on DNS server: */5 * * * * curl http://10.0.0.1:4400/ -o /etc/dhcp_hosts | |
from http.server import BaseHTTPRequestHandler, HTTPServer | |
import re | |
from ipaddress import ip_network, ip_address | |
class S(BaseHTTPRequestHandler): | |
def do_GET(self): | |
output = build_hosts() | |
self.send_response(200) | |
self.send_header('Content-type', 'text/plain') | |
self.end_headers() | |
self.wfile.write(output) | |
def build_hosts(): | |
matcher = re.compile(r'lease (10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) {.+?(?:client-hostname "((?:[^\"]|\\")*)";)?.}', | |
re.S) | |
output = b'' | |
# TODO: see if we can split-horizon this and return the correct | |
# gateway for the subnet we're being queried from | |
output += b'10.0.0.1 gaff.doyl.net\n' | |
with open('/config/dhcpd.leases') as f: | |
data = f.read() | |
matches = re.findall(matcher, data) | |
for (ip, host) in matches: | |
hostname = map_host(ip, host) | |
if hostname: | |
output += b' '.join([ip.encode('utf-8'), map_host(ip, host)]) + b'\n' | |
return output | |
def map_host(ip, client_hostname): | |
if not client_hostname: | |
return | |
client_hostname = client_hostname.encode('utf-8') | |
subnets = [ | |
(b'vm.gaff.doyl.net', ip_network('10.0.0.0/24')), | |
(b'tv.gaff.doyl.net', ip_network('10.1.0.0/24')), | |
] | |
ip = ip_address(ip) | |
for hostname, subnet in subnets: | |
if ip in subnet: | |
return b'.'.join([client_hostname, hostname]) | |
def main(): | |
httpd = HTTPServer(('', 4400), S) | |
print('Serving on port 4400') | |
httpd.serve_forever() | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment