Jim
Jim

Reputation: 623

python dns.resolver get DNS record type

I am learning how to use the python dns object. Quick question as I see many examples show methods of using the dns.resolver method with the DNS record type(CNAME, NS, etc). Is there a way to use this dns object to query a DNS name and pull it's resolution with the record type. Similar to what DIG supplies in the answer section.

Thanks,

Jim

Upvotes: 4

Views: 23143

Answers (5)

Mike Barkas
Mike Barkas

Reputation: 51

You can get the type with rdatatype

>>> import dns.resolver
>>> answer = dns.resolver.query('google.com')
>>> rdt = dns.rdatatype.to_text(answer.rdtype)
>>> print(rdt)
A

Upvotes: 5

Naoy
Naoy

Reputation: 146

The only check I found so far to determine if it's A or CNAME answer is to test if qname attribute is equal to canonical_name attribute.

answer = dns.resolver.query('www.example.com')
if answer.qname == answer.canonical_name:
    print "This is A record"
else:
    print "This isn't A, probably CNAME..."

Upvotes: 2

Joe H
Joe H

Reputation: 71

Here's an example of a CNAME:

>>> cname = dns.resolver.query("mail.unixy.net", 'CNAME')
>>> for i in cname.response.answer:
...     for j in i.items:
...             print j.to_text()
... 
unixy.net.

TXT:

>>> txt = dns.resolver.query("unixy.net", 'TXT')
>>> for i in txt.response.answer:
...     for j in i.items:
...             print j.to_text()
... 
"v=spf1 ip4:..."

NS:

>>> ns = dns.resolver.query("unixy.net", 'NS')
>>> for i in ns.response.answer:
...     for j in i.items:
...             print j.to_text()
... 
ns2.unixy.net.
ns1.unixy.net.

You can get most records following the same pattern. Multiple responses queries are stored in a list. So looping is sometimes necessary (ex:multiple A and NS recs).

Upvotes: 3

brianray
brianray

Reputation: 1169

How about this?

In [1]: import dns.resolver

In [2]: dns.resolver.query('chipy.org').__dict__
Out[2]: 
{'canonical_name': <DNS name chipy.org.>,
 'expiration': 1304632023.2383349,
 'qname': <DNS name chipy.org.>,
 'rdclass': 1,
 'rdtype': 1,
 'response': <DNS message, ID 64039>,
 'rrset': <DNS chipy.org. IN A RRset>}

Upvotes: 0

h0tw1r3
h0tw1r3

Reputation: 6818

Looks like you need to roll your own Resolver class. The Answer objects returned by calling dns.resolver.query only contain the record(s) which specifically match the request, which happens to be an A record by default. It's all there, the trail is lost along the way. If you print the response you can see what I mean.

#!/usr/bin/env python

import dns.resolver

answer = dns.resolver.query('www.clarkmania.com')
print answer.response
print "------"
print answer.rrset

Upvotes: 0

Related Questions