| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
# Two ways of querying a specific nameserver. |
| 4 |
|
| 5 |
import dns.message |
| 6 |
import dns.query |
| 7 |
import dns.rdataclass |
| 8 |
import dns.rdatatype |
| 9 |
|
| 10 |
# This way is just like nslookup/dig: |
| 11 |
|
| 12 |
qname = dns.name.from_text("amazon.com") |
| 13 |
q = dns.message.make_query(qname, dns.rdatatype.NS) |
| 14 |
print("The query is:") |
| 15 |
print(q) |
| 16 |
print("") |
| 17 |
r = dns.query.udp(q, "8.8.8.8") |
| 18 |
print("The response is:") |
| 19 |
print(r) |
| 20 |
print("") |
| 21 |
print("The nameservers are:") |
| 22 |
ns_rrset = r.find_rrset(r.answer, qname, dns.rdataclass.IN, dns.rdatatype.NS) |
| 23 |
for rr in ns_rrset: |
| 24 |
print(rr.target) |
| 25 |
print("") |
| 26 |
print("") |
| 27 |
|
| 28 |
# A higher-level way: |
| 29 |
|
| 30 |
import dns.resolver |
| 31 |
|
| 32 |
answer = dns.resolver.resolve_at("8.8.8.8", "amazon.com", "NS") |
| 33 |
print("The nameservers are:") |
| 34 |
for rr in answer: |
| 35 |
print(rr.target) |
| 36 |
print("") |
| 37 |
print("") |
| 38 |
|
| 39 |
# If you're going to make a bunch of queries to the server, make the resolver once |
| 40 |
# and then use it multiple times: |
| 41 |
|
| 42 |
res = dns.resolver.make_resolver_at("dns.google") |
| 43 |
answer = res.resolve("amazon.com", "NS") |
| 44 |
print("The amazon.com nameservers are:") |
| 45 |
for rr in answer: |
| 46 |
print(rr.target) |
| 47 |
answer = res.resolve("google.com", "NS") |
| 48 |
print("The google.com nameservers are:") |
| 49 |
for rr in answer: |
| 50 |
print(rr.target) |
| 51 |
print("") |
| 52 |
print("") |
| 53 |
|
| 54 |
# Sending a query with the all flags set to 0. This is the easiest way |
| 55 |
# to make a query with the RD flag off. |
| 56 |
# |
| 57 |
# This sends a query with RD=0 for the root SOA RRset to the IP address |
| 58 |
# for l.root-servers.net. |
| 59 |
|
| 60 |
q = dns.message.make_query(".", dns.rdatatype.SOA, flags=0) |
| 61 |
r = dns.query.udp(q, "199.7.83.42") |
| 62 |
print("\nThe flags in the response are {}".format(dns.flags.to_text(r.flags))) |
| 63 |
print('The SOA in the response is "{}"'.format((r.answer)[0][0])) |