Christopher Long
Christopher Long

Reputation: 904

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.

Upvotes: 25

Views: 60815

Answers (3)

Rotem jackoby
Rotem jackoby

Reputation: 22128

Found 2 additional Python libraries for dig-like commands.
Both of them are called pydig.

1 ) leonsmith/pydig

Installation:
pip install pydig

Usage:

>>> import pydig
>>> pydig.query('example.com', 'A')
['93.184.216.34']
>>> pydig.query('www.github.com', 'CNAME')
['github.com.']
>>> pydig.query('example.com', 'NS')
['a.iana-servers.net.', 'b.iana-servers.net.']

2 ) shuque/pydig.

Installation:
(as root) python3 setup.py install

Usage:

   pydig www.example.com
   pydig www.example.com A
   pydig www.example.com A IN
   pydig @10.0.1.2 example.com MX
   pydig @dns1.example.com _blah._tcp.foo.example.com SRV
   pydig @192.168.42.6 +dnssec +norecurse blah.example.com NAPTR
   pydig @dns2.example.com -6 +hex www.example.com
   pydig @192.168.72.3 +walk secure.example.com

Upvotes: 3

koblas
koblas

Reputation: 27068

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

Upvotes: 57

unutbu
unutbu

Reputation: 879481

os.system is deprecated. Use subprocess.Popen:

import subprocess
import shlex

cmd='dig @ns1.netnames.net www.rac.co.uk +short'
# cmd='dig @ns1.netnames.net www.rac.co.uk CNAME'
proc=subprocess.Popen(shlex.split(cmd),stdout=subprocess.PIPE)
out,err=proc.communicate()
print(out)
# rac-secure.gslb.norwichunion.com.

Upvotes: 8

Related Questions