about summary refs log tree commit diff
path: root/tools/dnsmasq-leases-html/dnsmasq-leases-html.py
blob: c1f03dbb43a63bfdca9e0ac66862ae034ca5a80a (plain) (blame)
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
#!/usr/bin/env python3

import datetime
import ipaddress
import os

from jinja2 import Environment, FileSystemLoader


outfile = os.getenv("DNSMASQ_LEASES_OUT", "/var/lib/dnsmasq/leases.html")
leases_file = os.getenv("DNSMASQ_LEASES", "/var/lib/dnsmasq/dnsmasq.leases")

leases = []

with open(leases_file, "r") as f:
    for line in f:
        content = line.rstrip("\n").split(" ")
        lease = dict()
        if int(content[0]) == 0:
            lease["expire"] = "never"
        else:
            lease["expire"] = datetime.datetime.fromtimestamp(int(content[0]))
        lease["MAC"] = content[1]
        lease["IP"] = ipaddress.ip_address(content[2])
        lease["hostname"] = content[3]
        leases.append(lease)

leases = sorted(leases, key=lambda d: d["IP"])

dir_path = os.path.dirname(os.path.realpath(__file__))
templates_dir = os.path.join(dir_path, "templates")
environment = Environment(loader=FileSystemLoader(templates_dir))
template = environment.get_template("index.html")

content = template.render(leases=leases)
with open(outfile, "w") as fh:
    print(content, file=fh)