reverse.py 1.4 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. from typing import Dict, List # pylint: disable=unused-import
  23. reverse_map = {} # type: Dict[str, List[str]]
  24. for filename in sys.argv[1:]:
  25. zone = dns.zone.from_file(filename, os.path.basename(filename),
  26. relativize=False)
  27. for (name, ttl, rdata) in zone.iterate_rdatas('A'):
  28. print(type(rdata))
  29. try:
  30. reverse_map[rdata.address].append(name.to_text())
  31. except KeyError:
  32. reverse_map[rdata.address] = [name.to_text()]
  33. for k in sorted(reverse_map.keys(), key=dns.ipv4.inet_aton):
  34. v = reverse_map[k]
  35. v.sort()
  36. print(k, v)