pythondnscnamedig

Using the dig command in python


Just a forewarning, my python skills are almost nonexistent, but I’m trying to learn as I go.

I'm doing a few changes via our DNS control panel over the weekend to about 58 CNAMES (just changing the destination)

And rather than checking the changes have gone live for each individual record I was wondering if there was a way to script a list of digs for each CNAME in python?

The dig command I use would be something like this

dig @ns1.netnames.net www.rac.co.uk CNAME

and I would expect to see rac-secure.gslb2.rac.co.uk returned.

I tried something like:

import os
os.system( 'dig<exampledomain.com>'CNAME )

But that didn't appear to work (as I mentioned my python skills are lacking), am I on the right path, or should I be using something like dnspython? I have used the dnspython module before with (a lot) of help from the stack overflow community but I find the documentation really confusing.

Any pointers in the right direction would be greatly appreciated.

Regards

Chris.


Solution

  • It's quite possible to invoke dig from python, it would probably save you work to just use a python library. Take a look at dnspython which will probably do everything easier - plus you don't have to parse the output format.

    import socket
    import dns.resolver
    
    # Basic query
    for rdata in dns.resolver.query('www.yahoo.com', 'CNAME') :
        print rdata.target
    
    # Set the DNS Server
    resolver = dns.resolver.Resolver()
    resolver.nameservers=[socket.gethostbyname('ns1.cisco.com')]
    for rdata in resolver.query('www.yahoo.com', 'CNAME') :
        print rdata.target