Skip to content

Instantly share code, notes, and snippets.

@yousefamar
Created October 19, 2017 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yousefamar/f9e8f415bdf248241e9a4b3ae10bea79 to your computer and use it in GitHub Desktop.
Save yousefamar/f9e8f415bdf248241e9a4b3ae10bea79 to your computer and use it in GitHub Desktop.
Prints hostnames (found in dns.log) corresponding to MAC addresses (found in dhcp.log)
#!/usr/bin/python3
import subprocess
from collections import defaultdict
import sys
#IPsByMAC = defaultdict(list)
#proc = subprocess.Popen('cat dhcp.log | bro-cut ts mac assigned_ip', shell=True, stdout=subprocess.PIPE)
#while True:
# line = proc.stdout.readline()
# if not line or line == '':
# break
# ts, mac, ip = line.decode('utf8').strip().split('\t')
# ts = float(ts)
# IPsByMAC[mac].append([ts, ip])
#
##for mac, info in IPsByMAC.items():
## print(mac)
## for i in info:
## print('\t ' + str(info))
MACsByIP = defaultdict(list)
proc = subprocess.Popen('cat dhcp.log | bro-cut ts mac assigned_ip', shell=True, stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if not line or line == '':
break
ts, mac, ip = line.decode('utf8').strip().split('\t')
ts = float(ts)
MACsByIP[ip].append([ts, mac])
#for ip, info in MACsByIP.items():
# print(ip)
# for i in info:
# print('\t ' + str(info))
hostnamesByIP = defaultdict(list)
proc = subprocess.Popen('cat dns.log | bro-cut ts query answers', shell=True, stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if not line or line == '':
break
ts, hostname, ips = line.decode('utf8').strip().split('\t')
ts = float(ts)
ips = ips.split(',')
for ip in ips:
# If it's the same as the most recent, don't bother adding (no change)
if ip not in hostnamesByIP or hostnamesByIP[ip][-1][1] is not hostname:
hostnamesByIP[ip].append([ts, hostname])
#for ip, info in hostnamesByIP.items():
# print(ip)
# for i in info:
# print('\t ' + str(info))
hostnamesByMAC = defaultdict(set)
for ip, macs in MACsByIP.items():
if ip not in hostnamesByIP:
sys.stderr.write('Warning: No hostnames for IP ' + ip + '\n')
continue
for ts0, mac in macs:
for ts1, hostname in hostnamesByIP[ip]:
if ts1 > ts0:
hostnamesByMAC[mac].add(hostname)
break
# TODO
for mac, hostnames in hostnamesByMAC.items():
print(mac)
for hostname in hostnames:
print('\t ' + hostname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment