#!/bin/python3 # import subprocess import time class host(object): def __init__(self): self.mac = '' self.ip = '' self.vlan = 0 self.state = '' self.hostname = '' self.lease_tm = 0 def __str__(self): return "%-16s - %17s - %-10s - %15s - %s" % (self.ip, self.mac, self.state, time.asctime(time.localtime(self.lease_tm)), self.hostname) class hostlist(dict): def __init__(self): dict.__init__(self) def append(self, host): if host.mac in self: if host.state < self[host.mac].state: self[host.mac] = host else: self[host.mac] = host def __str__(self): rv = "" for key in self: rv += str(self[key]) + '\n' return rv hl = hostlist() # # ip n # for line in subprocess.check_output(['ip', 'n']).decode('utf-8').split('\n'): data = line.split(" ") h = host() h.ip = data[0] try: h.vlan = int(h.ip.split('.')[2]) except IndexError: pass if len(data) == 6: h. mac = data[4] h.state = data[5] else: continue hl.append(h) # # leases # with open('/var/lib/misc/dnsmasq.leases', 'r') as fh: for line in fh.read().split('\n'): data = line.split(' ') if len(data) == 5: h = hl.get(data[1], host()) h.lease_tm = int(data[0]) h.mac = data[1] h.ip = data[2] try: h.vlan = int(h.ip.split('.')[2]) except IndexError: pass h.hostname = data[3] if h.mac not in hl: hl.append(h) for vlan in [20, 30, 40, 50, 60, 90]: print("Hosts in VLAN %d" % vlan) for host in hl.values(): if host.vlan == vlan: print(" *", host) print()