printer_browser.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #!/usr/bin/env python3
  2. """
  3. Browse for printers on the local net, dump DNS records for inclusion
  4. in a DNS zone in master file format.
  5. """
  6. from argparse import ArgumentParser, FileType, ArgumentDefaultsHelpFormatter
  7. from zeroconf import Zeroconf, ServiceBrowser, ServiceInfo
  8. from socket import inet_ntop, AF_INET, AF_INET6
  9. from dns.rdataclass import IN
  10. from dns.rdatatype import PTR, SRV, TXT
  11. from dns.rrset import RRset
  12. class Listener:
  13. """
  14. mDNS browser, receives service advertisements, retrieves
  15. ServiceInfo records and drops them into a Queue for pickup.
  16. """
  17. try:
  18. from queue import Queue, Empty # Python 3
  19. except ImportError:
  20. from Queue import Queue, Empty # Python 2
  21. def __init__(self, args):
  22. self.q = self.Queue()
  23. self.browse_timeout = args.browse_timeout
  24. self.query_timeout = args.query_timeout * 1000
  25. def add_service(self, z, type, name):
  26. printer = z.get_service_info(type, name, timeout = self.query_timeout)
  27. if printer is not None:
  28. self.q.put(printer)
  29. def remove_service(self, z, type, name):
  30. pass
  31. def get(self):
  32. "Iterator to retrieve ServiceInfo results"
  33. while True:
  34. try:
  35. yield self.q.get(timeout = self.browse_timeout)
  36. except self.Empty:
  37. return
  38. def dns_name(name, prefix = (), suffix = ()):
  39. "Strip .local, add optional prefix and suffix."
  40. from dns.name import Name, from_text
  41. name = from_text(str(name))
  42. assert name.labels[-2:] == (b"local", b"")
  43. return Name(prefix + name.labels[:-2] + suffix)
  44. def rr(name, rdata):
  45. r = RRset(name, rdata.rdclass, rdata.rdtype)
  46. r.add(rdata)
  47. return r
  48. def txt_rr(printer):
  49. "Regenerate ServiceInfo from property list and generate a TXT RR."
  50. from dns.rdata import from_wire
  51. si = ServiceInfo(printer.type, printer.name, properties = printer.properties)
  52. return rr(dns_name(printer.name), from_wire(IN, TXT, si.text, 0, len(si.text)))
  53. def srv_rr(printer):
  54. "Generate an SRV RR."
  55. from dns.rdtypes.IN.SRV import SRV as SRV_RR
  56. return rr(dns_name(printer.name), SRV_RR(IN, SRV, printer.priority, printer.weight, printer.port, dns_name(printer.server)))
  57. def ptr_rr(printer, *prefix):
  58. "Generate a PTR RR."
  59. from dns.rdtypes.ANY.PTR import PTR as PTR_RR
  60. return rr(dns_name(printer.type, prefix = prefix), PTR_RR(IN, PTR, dns_name(printer.name)))
  61. def main():
  62. ap = ArgumentParser(description = __doc__, formatter_class = ArgumentDefaultsHelpFormatter)
  63. ap.add_argument("-q", "--quiet", action = "store_true",
  64. help = "omit comments from generated master file text")
  65. ap.add_argument("-o", "--output", type = FileType("w"), default = "-",
  66. help = "where to write master file text")
  67. ap.add_argument("--browse-timeout", type = int, default = 5,
  68. help = "timeout in seconds while browsing for printers")
  69. ap.add_argument("--query-timeout", type = int, default = 3,
  70. help = "timeout in seconds to retrieve printer data")
  71. ap.add_argument("--keep-adminurl", action = "store_true",
  72. help = "keep adminurl property in generated DNS data")
  73. ap.add_argument("mdns_type", nargs = "*",
  74. default = ["_ipp._tcp.local.", "_universal._sub._ipp._tcp.local.", "_pdl-datastream._tcp.local."],
  75. help = "mDNS types for which to browse")
  76. args = ap.parse_args()
  77. def write(s = ""):
  78. args.output.write("{!s}\n".format(s))
  79. printers = {}
  80. z = Zeroconf()
  81. listener = Listener(args)
  82. for mdns_type in args.mdns_type:
  83. ServiceBrowser(z, mdns_type, listener)
  84. for printer in listener.get():
  85. try:
  86. printers[printer.name].append(printer)
  87. except KeyError:
  88. printers[printer.name] = [printer]
  89. z.close()
  90. for printer in printers.values():
  91. rrs = [ptr_rr(p) for p in printer]
  92. p = printer[0]
  93. if not args.keep_adminurl:
  94. p.properties.pop(b"adminurl", None)
  95. rrs.append(srv_rr(p))
  96. rrs.append(txt_rr(p))
  97. if not args.quiet:
  98. addr = inet_ntop({4:AF_INET, 6:AF_INET6}[len(p.address)], p.address)
  99. write(";; Name: {!r}".format(p.name))
  100. write(";; Addr: {} ({})".format(addr, p.server))
  101. write(";;")
  102. for rr in rrs:
  103. write(rr)
  104. write()
  105. if __name__ == "__main__":
  106. main()