-
Notifications
You must be signed in to change notification settings - Fork 4
/
test_dns.py
executable file
·97 lines (70 loc) · 2.5 KB
/
test_dns.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/env python
# -*- test-case-name: twisted.names.test.test_examples -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Print the Address records, Mail-Exchanger records and the Nameserver
records for the given domain name. eg
python testdns.py google.com
"""
import sys
from twisted.internet import defer
from twisted.internet.task import react
from twisted.names import client, dns, error
from twisted.python import usage
class Options(usage.Options):
synopsis = 'Usage: testdns.py DOMAINNAME'
def parseArgs(self, domainname):
self['domainname'] = domainname
def formatRecords(records, heading):
"""
Extract only the answer records and return them as a neatly
formatted string beneath the given heading.
"""
answers, authority, additional = records
lines = ['# ' + heading]
for a in answers:
line = [
a.name,
dns.QUERY_CLASSES.get(a.cls, 'UNKNOWN (%d)' % (a.cls,)),
a.payload]
lines.append(' '.join(str(word) for word in line))
return '\n'.join(line for line in lines)
def printResults(results, domainname):
"""
Print the formatted results for each DNS record type.
"""
sys.stdout.write('# Domain Summary for %r\n' % (domainname,))
sys.stdout.write('\n\n'.join(results) + '\n')
def printError(failure, domainname):
"""
Print a friendly error message if the hostname could not be
resolved.
"""
failure.trap(defer.FirstError)
failure = failure.value.subFailure
failure.trap(error.DNSNameError)
sys.stderr.write('ERROR: domain name not found %r\n' % (domainname,))
def main(reactor, *argv):
options = Options()
try:
options.parseOptions(argv)
except usage.UsageError as errortext:
sys.stderr.write(str(options) + '\n')
sys.stderr.write('ERROR: %s\n' % (errortext,))
raise SystemExit(1)
domainname = options['domainname']
r = client.Resolver('/etc/resolv.conf')
d = defer.gatherResults([
r.lookupAddress(domainname).addCallback(
formatRecords, 'Addresses'),
r.lookupMailExchange(domainname).addCallback(
formatRecords, 'Mail Exchangers'),
r.lookupNameservers(domainname).addCallback(
formatRecords, 'Nameservers'),
], consumeErrors=True)
d.addCallback(printResults, domainname)
d.addErrback(printError, domainname)
return d
if __name__ == '__main__':
react(main, sys.argv[1:])