| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
__all__ = [ |
| 24 |
'get_txt' |
| 25 |
] |
| 26 |
|
| 27 |
|
| 28 |
def get_txt_dnspython(name, timeout=5): |
| 29 |
"""Return a TXT record associated with a DNS name.""" |
| 30 |
import dkim |
| 31 |
try: |
| 32 |
a = dns.resolver.resolve(name, dns.rdatatype.TXT,raise_on_no_answer=False, lifetime=timeout, search=True) |
| 33 |
for r in a.response.answer: |
| 34 |
if r.rdtype == dns.rdatatype.TXT: |
| 35 |
return b"".join(list(r.items)[0].strings) |
| 36 |
except dns.resolver.NXDOMAIN: pass |
| 37 |
except dns.resolver.NoNameservers: pass |
| 38 |
except dns.resolver.NoResolverConfiguration as e: |
| 39 |
raise dkim.DnsTimeoutError('dns.resolver.NoResolverConfiguration: {0}'.format(e)) |
| 40 |
except dns.exception.Timeout as e: |
| 41 |
raise dkim.DnsTimeoutError('dns.exception.Timeout: {0}'.format(e)) |
| 42 |
return None |
| 43 |
|
| 44 |
|
| 45 |
def get_txt_pydns(name, timeout=5): |
| 46 |
"""Return a TXT record associated with a DNS name.""" |
| 47 |
|
| 48 |
if name.endswith('.'): |
| 49 |
name = name[:-1] |
| 50 |
response = DNS.DnsRequest(name, qtype='txt', timeout=timeout).req() |
| 51 |
if not response.answers: |
| 52 |
return None |
| 53 |
for answer in response.answers: |
| 54 |
if answer['typename'].lower() == 'txt': |
| 55 |
return b''.join(answer['data']) |
| 56 |
return None |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
def get_txt_Milter_dns(name, timeout=5): |
| 61 |
"""Return a TXT record associated with a DNS name.""" |
| 62 |
|
| 63 |
if name.endswith('.'): |
| 64 |
name = name[:-1] |
| 65 |
sess = Session() |
| 66 |
a = sess.dns(name.encode('idna'),'TXT') |
| 67 |
if a: return b''.join(a[0]) |
| 68 |
return None |
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
try: |
| 73 |
import dns.resolver |
| 74 |
_get_txt = get_txt_dnspython |
| 75 |
except ImportError: |
| 76 |
try: |
| 77 |
import DNS |
| 78 |
DNS.DiscoverNameServers() |
| 79 |
_get_txt = get_txt_pydns |
| 80 |
except: |
| 81 |
raise |
| 82 |
|
| 83 |
|
| 84 |
def get_txt(name, timeout=5): |
| 85 |
"""Return a TXT record associated with a DNS name. |
| 86 |
|
| 87 |
@param name: The bytestring domain name to look up. |
| 88 |
""" |
| 89 |
|
| 90 |
try: |
| 91 |
unicode_name = name.decode('UTF-8') |
| 92 |
except UnicodeDecodeError: |
| 93 |
return None |
| 94 |
txt = _get_txt(unicode_name, timeout) |
| 95 |
if type(txt) is str: |
| 96 |
txt = txt.encode('utf-8') |
| 97 |
return txt |