s4-python: import a copy of the python dns library
[idra/samba.git] / source4 / scripting / python / samba_external / dnspython / examples / reverse.py
1 #!/usr/bin/env python
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 dns.zone
20 import dns.ipv4
21 import os.path
22 import sys
23
24 reverse_map = {}
25
26 for filename in sys.argv[1:]:
27     zone = dns.zone.from_file(filename, os.path.basename(filename),
28                               relativize=False)
29     for (name, ttl, rdata) in zone.iterate_rdatas('A'):
30         try:
31             reverse_map[rdata.address].append(name.to_text())
32         except KeyError:
33             reverse_map[rdata.address] = [name.to_text()]
34
35 keys = reverse_map.keys()
36 keys.sort(lambda a1, a2: cmp(dns.ipv4.inet_aton(a1), dns.ipv4.inet_aton(a2)))
37 for k in keys:
38     v = reverse_map[k]
39     v.sort()
40     print k, v