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