Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

dns - How can I run MX record lookup fall back to A record in Python

I am trying to run a code with following conditions:

  1. Use MX record lookup and pick the lowest priority (in MX, lowest number is the highest preference)

  2. if MX is not available or not responding, try A record

  3. if None of the above is available, print bad record

I have run the following code:

import dns.resolver

#this reads from a file that has the to domain which is gmail.com
from SMTP_Server.Tests.Envlope import to_domain

records = dns.resolver.resolve(to_domain, 'MX')[0]
print(records)

if records == None:
   records = dns.resolver.resolve(to_domain, 'A')
   print(records)
else:
    raise ValueError("Bad Record")

But I am getting an error even though it does show mx record:

40 alt4.gmail-smtp-in.l.google.com.

    raise ValueError("Bad Record")
ValueError: Bad Record

Any assistance is appreciated

question from:https://stackoverflow.com/questions/65835763/how-can-i-run-mx-record-lookup-fall-back-to-a-record-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are trying to resolve "40 someurl.com.". please get rid of the number at the beggining and of the dot at the very end. You are also not looking up for any preference, you are justing picking the first entry. And lastly, you are checking for None when should be not None.

The correct would be:

import dns.resolver

to_domain = 'gmail.com'

records = dns.resolver.query(to_domain, 'MX')
lowestnumber = None
bestdomain = None
for r in records:
  t = r.to_text()
  i = t.find(' ')
  n = int(t[:i])
  if lowestnumber is None or n < lowestnumber:
    lowestnumber = n
    bestdomain = t[n+1:-1] # here we skip the initial number and the final dot

if bestdomain is not None:
  records = dns.resolver.query(bestdomain, 'A')
  for r in records:
    print(r.to_text())
else:
  raise ValueError('Bad Record')

At least for me, it is dns.resolver.query instead of dns.resolver.resolve. Please make your adaptations to make it to work for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...