Last active
November 15, 2015 20:30
-
-
Save descilla/d24453fdf0b7c508b0e4 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/python | |
import datetime | |
from pprint import pprint | |
def parse_leases(lease_file): | |
leases = {} | |
lease = {} | |
in_lease = False | |
for line in lease_file: | |
if line.lstrip().startswith('#'): | |
continue | |
tokens = line.split() | |
if len(tokens) == 0: | |
continue | |
key = tokens[0].lower() | |
if key == 'lease': | |
if in_lease: | |
raise Exception('Parsing error') | |
else: | |
in_lease = True | |
lease = {'id' : tokens[1]} | |
elif key == 'starts' or key == 'ends': | |
if not in_lease: | |
raise Exception('Parsing error') | |
else: | |
lease[key] = datetime.datetime.strptime(tokens[2]+' '+tokens[3].rstrip(';'), '%Y/%m/%d %H:%M:%S') | |
elif key == '}': | |
in_lease = False | |
leases[lease['id']] = lease | |
lease = {} | |
return leases | |
def count_active_leases(all_leases, now): | |
count = 0 | |
for lease in all_leases.itervalues(): | |
if timestamp_inbetween(now, lease['starts'], lease['ends']): | |
count += 1 | |
return count | |
def timestamp_inbetween(now, start, end): | |
return start < now < end | |
myfile = open('/var/lib/dhcp/dhcpd.leases', 'r') | |
all_leases = parse_leases(myfile) | |
count = count_active_leases(all_leases, datetime.datetime.utcnow()) | |
print count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment