0

I have the simple python code for grabbing NS records of a domain:

#!/usr/bin/python
import socket
import dns.resolver
domain = 'google.com'
resp = dns.resolver.query(domain, 'NS')
for d in resp:
    ns = d.to_text()
    nsip = socket.gethostbyname(ns)
    print ns, nsip

And sample result is something like:

ns2.google.com. 216.239.34.10
ns1.google.com. 216.239.32.10
ns3.google.com. 216.239.36.10
ns4.google.com. 216.239.38.10
ns5.google.com. 216.5.5.5

But I want to remove printing repetitive ips from the output like so:

IP: 216.239.32.10
    ns2.google.com., ns1.google.com., ns3.google.com., ns4.google.com.

IP: 216.5.5.5
    ns5.google.com. 

How can I do that?

yasin
  • 107
  • 10

1 Answers1

0

You can use defaultdict,

In [10]: from collections import defaultdict
In [11]: ns = [['ns2.google.com.', '216.239.32.10'], ['ns1.google.com.', '216.239.32.10'], ['ns3.google.com.', '216.239.36.10'], ['ns4.google.c
    ...: om.', '216.239.38.10'], ['ns5.google.com.', '216.5.5.5']]

In [12]: d = defaultdict(list)
In [13]: for v,k in ns:
    ...:     d[k].append(v)

In [14]: print d
Out[14]: 
defaultdict(list,
            {'216.239.32.10': ['ns2.google.com.', 'ns1.google.com.'],
             '216.239.36.10': ['ns3.google.com.'],
             '216.239.38.10': ['ns4.google.com.'],
             '216.5.5.5': ['ns5.google.com.']})

The output you want to print,

In [16]: for k,v in d.items():
    ...:     print "IP: {}".format(k)
    ...:     print "\t{}".format(', '.join(v))
    ...:     
IP: 216.239.36.10
    ns3.google.com.
IP: 216.239.32.10
    ns2.google.com., ns1.google.com.
IP: 216.5.5.5
    ns5.google.com.
IP: 216.239.38.10
    ns4.google.com.

        ...:     
Rahul K P
  • 15,740
  • 4
  • 35
  • 52