|
@@ -0,0 +1,93 @@
|
|
1
|
+#!/bin/python3
|
|
2
|
+#
|
|
3
|
+import subprocess
|
|
4
|
+import time
|
|
5
|
+
|
|
6
|
+class host(object):
|
|
7
|
+ def __init__(self):
|
|
8
|
+ self.mac = ''
|
|
9
|
+ self.ip = ''
|
|
10
|
+ self.vlan = 0
|
|
11
|
+ self.state = ''
|
|
12
|
+ self.hostname = ''
|
|
13
|
+ self.lease_tm = 0
|
|
14
|
+
|
|
15
|
+ def sortcriteria(h):
|
|
16
|
+ rv = h.hostname if h.hostname != '*' else '~'
|
|
17
|
+ rv += ".".join(["%03d" % int(v) for v in h.ip.split('.')])
|
|
18
|
+ return rv.lower()
|
|
19
|
+
|
|
20
|
+ def __str__(self):
|
|
21
|
+ return " * %-16s - %17s - %-10s - %15s - %s" % (self.ip, self.mac, self.state, time.asctime(time.localtime(self.lease_tm)), self.hostname)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+class hostlist(dict):
|
|
25
|
+ def __init__(self):
|
|
26
|
+ dict.__init__(self)
|
|
27
|
+
|
|
28
|
+ def append(self, host):
|
|
29
|
+ if host.mac in self:
|
|
30
|
+ if host.state < self[host.mac].state:
|
|
31
|
+ self[host.mac] = host
|
|
32
|
+ else:
|
|
33
|
+ self[host.mac] = host
|
|
34
|
+
|
|
35
|
+ def vlan_list(self, vlan):
|
|
36
|
+ rv = hostlist()
|
|
37
|
+ for h in self.values():
|
|
38
|
+ if h.vlan == vlan:
|
|
39
|
+ rv.append(h)
|
|
40
|
+ return rv
|
|
41
|
+
|
|
42
|
+ def __str__(self):
|
|
43
|
+ entries = list(self.values())
|
|
44
|
+ entries.sort(key=host.sortcriteria)
|
|
45
|
+ rv = ""
|
|
46
|
+ for h in entries:
|
|
47
|
+ rv += str(h) + '\n'
|
|
48
|
+ return rv
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+hl = hostlist()
|
|
52
|
+
|
|
53
|
+#
|
|
54
|
+# ip n
|
|
55
|
+#
|
|
56
|
+for line in subprocess.check_output(['ip', 'n']).decode('utf-8').split('\n'):
|
|
57
|
+ data = line.split(" ")
|
|
58
|
+ h = host()
|
|
59
|
+ h.ip = data[0]
|
|
60
|
+ try:
|
|
61
|
+ h.vlan = int(h.ip.split('.')[2])
|
|
62
|
+ except IndexError:
|
|
63
|
+ pass
|
|
64
|
+ if len(data) == 6:
|
|
65
|
+ h. mac = data[4]
|
|
66
|
+ h.state = data[5]
|
|
67
|
+ else:
|
|
68
|
+ continue
|
|
69
|
+ hl.append(h)
|
|
70
|
+
|
|
71
|
+#
|
|
72
|
+# leases
|
|
73
|
+#
|
|
74
|
+with open('/var/lib/misc/dnsmasq.leases', 'r') as fh:
|
|
75
|
+ for line in fh.read().split('\n'):
|
|
76
|
+ data = line.split(' ')
|
|
77
|
+ if len(data) == 5:
|
|
78
|
+ h = hl.get(data[1], host())
|
|
79
|
+ h.lease_tm = int(data[0])
|
|
80
|
+ h.mac = data[1]
|
|
81
|
+ h.ip = data[2]
|
|
82
|
+ try:
|
|
83
|
+ h.vlan = int(h.ip.split('.')[2])
|
|
84
|
+ except IndexError:
|
|
85
|
+ pass
|
|
86
|
+ h.hostname = data[3]
|
|
87
|
+ if h.mac not in hl:
|
|
88
|
+ hl.append(h)
|
|
89
|
+
|
|
90
|
+for vlan in [20, 30, 40, 50, 60, 90]:
|
|
91
|
+ print("Hosts in VLAN %d" % vlan)
|
|
92
|
+ print(hl.vlan_list(vlan))
|
|
93
|
+ print()
|