Skip to content

Instantly share code, notes, and snippets.

@tasoseng
Created March 27, 2021 00:12
Show Gist options
  • Save tasoseng/46f2aa7d7498c1093b139d9a9b97745b to your computer and use it in GitHub Desktop.
Save tasoseng/46f2aa7d7498c1093b139d9a9b97745b to your computer and use it in GitHub Desktop.
print active openbsd dhcpd leases
#!/usr/bin/env python
# coding: UTF-8
# for openbsd dhcpd only
# apo dhcpd.leases(5):
# the last declaration is the current
# also, the times are in UTC!
import re
from datetime import datetime
import pytz
FILE="/var/db/dhcpd.leases"
UTC_NOW=datetime.utcnow()
local = pytz.timezone("Europe/Athens")
f=open(FILE)
text = f.read()
#result = re.finditer(r'^lease (?P<ip>[0-9.]+) {\n\tstarts \d (?P<start>\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2});\n\tends \d (?P<end>\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2});\n\thardware ethernet (?P<mac>[0-9a-f:]+);', text, re.M)
#result = re.finditer(r'^lease (?P<ip>.*) {\n\tstarts \d (?P<start>.*);\n\tends \d (?P<end>.*);\n\thardware ethernet (?P<mac>.*);(\n\tuid (.*);)*\n\tclient-hostname "(?P<name>.*)";', text, re.M)
result = re.finditer(r'^lease (?P<ip>.*) {\n\tstarts \d (?P<start>.*);\n\tends \d (?P<end>.*);\n\thardware ethernet (?P<mac>.*);', text, re.M)
d = dict()
for res in result:
r = res.groupdict()
ip = r.pop('ip')
end_time = datetime.strptime(r.pop('end'), "%Y/%m/%d %H:%M:%S")
if ( end_time > UTC_NOW ):
d[ip] = r
d[ip]['start'] = local.fromutc(datetime.strptime(r.pop('start'), "%Y/%m/%d %H:%M:%S"))
d[ip]['end'] = local.fromutc(end_time)
for ip, v in d.items():
print ip.ljust(16), v['mac'], v['start'], v['end'] #, v['name']
print 86*"-"
print str(len(d)) + " active leases."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment