reverse.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env python
  2. # Usage: reverse.py <zone_filename>...
  3. #
  4. # This demo script will load in all of the zones specified by the
  5. # filenames on the command line, find all the A RRs in them, and
  6. # construct a reverse mapping table that maps each IP address used to
  7. # the list of names mapping to that address. The table is then sorted
  8. # nicely and printed.
  9. #
  10. # Note! The zone name is taken from the basename of the filename, so
  11. # you must use filenames like "/wherever/you/like/dnspython.org" and
  12. # not something like "/wherever/you/like/foo.db" (unless you're
  13. # working with the ".db" GTLD, of course :)).
  14. #
  15. # If this weren't a demo script, there'd be a way of specifying the
  16. # origin for each zone instead of constructing it from the filename.
  17. from __future__ import print_function
  18. import dns.zone
  19. import dns.ipv4
  20. import os.path
  21. import sys
  22. reverse_map = {}
  23. for filename in sys.argv[1:]:
  24. zone = dns.zone.from_file(filename, os.path.basename(filename),
  25. relativize=False)
  26. for (name, ttl, rdata) in zone.iterate_rdatas('A'):
  27. try:
  28. reverse_map[rdata.address].append(name.to_text())
  29. except KeyError:
  30. reverse_map[rdata.address] = [name.to_text()]
  31. keys = reverse_map.keys()
  32. keys.sort(key=dns.ipv4.inet_aton)
  33. for k in keys:
  34. v = reverse_map[k]
  35. v.sort()
  36. print(k, v)