0

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

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Maskiin
  • 19
  • 6

2 Answers2

1

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.

brunoff
  • 4,161
  • 9
  • 10
-1

This is a simple logic mistake. The way you wrote it, if you get a good MX result (i.e. records != None), then it will raise an error.

Try this instead:

...

if records is None:
   records = dns.resolver.resolve(to_domain, 'A')
   print(records)

if records is None:
    raise ValueError("Bad Record")

I also switched the comparison from == to is for better practice. See What is the difference between "is None" and "== None"

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Thanks. When i changed as you suggested and test a domain doesn't have MX, but have an A record - first record i check, instead of moving to the second record i am getting the following error: *dns.resolver.NoAnswer: The DNS response does not contain an answer to the question: exampledomain.com. IN MX* – Maskiin Jan 22 '21 at 10:00
  • @Maskiin You'll need to catch it. See [Handling Exceptions - Python Tutorial](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) – wjandrea Jan 22 '21 at 15:50