Python modules you should know: dnspython

May 07, 2012 at 04:40 PM | categories: Python, PyMYSK, Howto | View Comments

Next in our series of Python modules you should know is dnspython. This package is a DNS toolkit, you can use it to perform DNS queries, Zone transfers and Dynamic Updates in Python programs.

Home page

Use

dnspython is a DNS toolkit for Python. It supports almost all record types. It can be used for queries, zone transfers, and dynamic updates. It supports TSIG authenticated messages and EDNS0.

dnspython provides both high and low level access to DNS. The high level classes perform queries for data of a given name, type, and class, and return an answer set. The low level classes allow direct manipulation of DNS zones, messages, names, and records.

Installation

pip install dnspython

Usage

Lookup DNS records (A, AAAA, MX, NS)

A Records

import dns.resolver
answers = dns.resolver.query('topdog.za.net', 'A')
for rdata in answers:
    print rdata.address

AAAA Records

import dns.resolver
answers = dns.resolver.query('topdog.za.net', 'AAAA')
for rdata in answers:
    print rdata.address

MX Records

import dns.resolver
answers = dns.resolver.query('topdog.za.net', 'MX')
for rdata in answers:
    print 'host', rdata.exchange, 'has preference', rdata.preference

NS Records

import dns.resolver
answers = dns.resolver.query('topdog.za.net', 'NS')
for rdata in answers:
    print rdata.to_text()

Transfer a Zone from a server.

import dns.zone
import dns.query
zone = dns.zone.from_xfr(dns.query.xfr('174.136.108.83', 'topdog.za.net'))
print "*" * 10, "A records", "*" * 10
for (name, ttl, rdata) in zone.iterate_rdatas('A'):
    print name, "with TTL", ttl, "points to", rdata
print "*" * 10, "MX records", "*" * 10
for (name, ttl, rdata) in zone.iterate_rdatas('MX'):
    print name, "with TTL", ttl, "points to", rdata
print "*" * 10, "NS records", "*" * 10
for (name, ttl, rdata) in zone.iterate_rdatas('NS'):
    print name, "with TTL", ttl, "points to", rdata

Generate reverse names

import dns.reversename
print dns.reversename.from_address('174.136.108.83')

Perform a Dynamic record update (example from documentation modified)

import dns.query
import dns.tsigkeyring
import dns.update
import sys

if __name__ == '__main__':
    keyring = dns.tsigkeyring.from_text({
        'host-example.' : 'XXXXXXXXXXXXXXXXXXXXXX=='
    })
    # Replace an A record
    update = dns.update.Update('example.com', keyring=keyring)
    update.replace('host', 300, 'a', sys.argv[1])
    response = dns.query.tcp(update, '10.0.0.1')

And there is more

There is more that can be done using this package please refer to the documentation.


blog comments powered by Disqus