Skip to content

Instantly share code, notes, and snippets.

@jquast
Created February 29, 2016 17:40
Show Gist options
  • Save jquast/8a6c658a8776cdcd307c to your computer and use it in GitHub Desktop.
Save jquast/8a6c658a8776cdcd307c to your computer and use it in GitHub Desktop.
bonjour-monitor.py
#!/usr/bin/env python
import threading
import traceback
import sys
import time
import Queue
protocols = {
'tcp': [
'apple-mobdev2',
'home-sharing',
'ipps',
'odproxy',
'ptservice',
'afpovertcp',
'ftp',
'http',
'ipp',
'printer',
'pdl-datastream',
'rfb',
'smb',
'sftp',
'ssh',
'telnet',
'workstation',
],
'udp': [
'net-assistant',
]
}
class TailInThread(threading.Thread):
""" Using an iterator, report data received to ``queue`` from a thread. """
def __init__(self, iterator):
""" Class constructor. """
self.iterator = iterator
self.queue = Queue.Queue()
self.stopped = False
self.error = None
super(TailInThread, self).__init__()
self.daemon = True
def run(self):
""" Thread entry point. """
try:
for line in self.iterator:
self.queue.put(line.rstrip())
except Exception:
self.error = traceback.format_exception_only(*sys.exc_info()[:2])[0]
print(('err', self.error))
finally:
self.stopped = True
def main():
import subprocess
tails = []
for proto, services in protocols.items():
for srv in services:
cmd_args = ['/usr/bin/dns-sd', '-B', '_{0}._{1}.'.format(srv, proto),]
proc = subprocess.Popen(cmd_args, stdout=subprocess.PIPE)
tail = TailInThread(iterator=iter(proc.stdout.readline, ''))
tail.start()
tails.append(tail)
# toss first 4 lines
#tail.queue.get()
#tail.queue.get()
#tail.queue.get()
while True:
for tail in tails:
while True:
if tail.error:
print((tail, tail.error))
sys.exit(1)
try:
print(tail.queue.get(block=False))
except Queue.Empty:
break
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment