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
19import dns.zone
20import dns.ipv4
21import os.path
22import sys
23from typing import Dict, List # pylint: disable=unused-import
24
25reverse_map = {} # type: Dict[str, List[str]]
26
27for filename in sys.argv[1:]:
28    zone = dns.zone.from_file(filename, os.path.basename(filename),
29                              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
37for k in sorted(reverse_map.keys(), key=dns.ipv4.inet_aton):
38    v = reverse_map[k]
39    v.sort()
40    print(k, v)
41