#!/usr/bin/env python import subprocess import re import time import hashlib timeout = 300 f_current = '/var/db/connect.current' f_gone = '/var/db/connect.gone' def interfaces(): infs=[] cmd = ['/usr/bin/grep','range','/usr/local/etc/dnsmasq.conf'] output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] for line in output.strip().split('\n'): inf = line.split('=')[1].split(',')[0] inf = inf.replace('ath', 'wlan') infs.append(inf) return infs def get_arp_list(inf): arp = {} output = subprocess.Popen(['/usr/sbin/arp','-na'], stdout=subprocess.PIPE).communicate()[0] for i in inf: for line in output.strip().split('\n'): if not 'expires' in line: continue if i not in line: continue t = re.split('[ ()]',line) ip, mac, time, inf = t[2],t[5],t[10],t[7] arp[ip]=(mac,time,inf) return arp def get_current(): try: file = open(f_current, 'r') current=file.readlines() file.close() currentmacs = [] for i in current: currentmacs.append((i.split()[0],i.split()[1],i.split()[2])) except IOError: return () return currentmacs def write_new(clients): currentmacs = get_current() t = int(time.time()) currentmacs=get_current() file = open(f_current, 'a') for dummy, data in clients.iteritems(): b=False for cur in currentmacs: if data[0] == cur[0]: b=True break if b: continue t2 = t + int(data[1]) - timeout file.write("%s %s %s\n" % (data[0],t2,data[2])) file.close() def diff_clients(arp, reg): gone = [] for client in reg: b=False for i in arp.values(): if client[0] == i[0] and client[2] == i[2]: b=True break if b: continue gone.append(client) return gone def clients_disc_gone(gone): t = int(time.time()) file = open(f_gone, 'a') for client in gone: t2 = t - ((t - int(client[1])) % timeout) hash = "" hash = hashlib.md5() hash.update(client[0]) macshort=client[0][0:8] file.write("%s %s %s %s %s %s\n" % (hash.hexdigest(), client[1], t2, client[2], macshort, client[0])) file.close() def clients_disc_current(gone,reg): new = [] for client in reg: b=False for i in gone: if client[0] == i[0]: b=True break if b: continue new.append(client) file=open(f_current, 'w') for line in new: file.write("%s %s %s\n" % (line[0], line[1], line[2])) file.close() # Get arp list arp = get_arp_list(interfaces()) # Write new arp entries to current write_new(arp) # Get all entries in current reg = get_current() # What is not in arp but is in current gone = diff_clients(arp, reg) # Write those entries to gone clients_disc_gone(gone) # Remove those entries from current clients_disc_current(gone,reg)