-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdhcp-lease-stats
executable file
·76 lines (64 loc) · 2 KB
/
dhcp-lease-stats
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#! /usr/bin/env python
#
"""
Print statistics about the DHCP leases.
"""
__docformat__ = 'reStructuredText'
from collections import defaultdict
from datetime import datetime
## main: run tests
# Example:
#
# lease 130.60.240.55 {
# starts 3 2010/04/14 14:54:38;
# ends 3 2010/04/14 17:54:38;
# tstp 3 2010/04/14 17:54:38;
# cltt 3 2010/04/14 14:54:38;
# binding state free;
# hardware ethernet 00:03:93:c1:8f:48;
# uid "\001\000\003\223\301\217H";
# }
#
def parse_dhcpd_leases(path='/var/lib/dhcp/dhcpd.leases'):
leases = defaultdict(dict)
file = open(path, 'r')
for line in file:
line = line.strip()
if line.startswith('lease'):
_, addr, _ = line.split(None, 2)
a1, a2, a3, a4 = addr.split('.')
prefix = ("%s.%s.%s" % (a1, a2, a3))
addr = a4
elif line.startswith('starts'):
_, _, timestamp = line.split(None, 2)
start = datetime.strptime(timestamp, '%Y/%m/%d %H:%M:%S;')
elif line.startswith('ends never'):
end = datetime(9999, 12, 31, 23, 59, 00)
elif line.startswith('ends'):
_, _, timestamp = line.split(None, 2)
end = datetime.strptime(timestamp, '%Y/%m/%d %H:%M:%S;')
elif line.startswith('binding state'):
_, _, state = line.split()
if state.startswith('free'):
state = 'free'
else:
state = 'used'
elif line.startswith('}'):
# commit values gathered so far
if start < datetime.now() < end:
leases[prefix][addr] = state
return leases
def count(D):
counts = defaultdict(int)
for v in D.values():
counts[v] += 1
return counts
def main():
leases = parse_dhcpd_leases()
for netprefix in leases.keys():
print ("%s:" % netprefix)
counts = count(leases[netprefix])
for state, num in counts.items():
print (" %s: %d" % (state, num))
if "__main__" == __name__:
main()