【问题标题】:How can I run MX record lookup fall back to A record in Python如何在 Python 中运行 MX 记录查找回退到 A 记录
【发布时间】:2021-01-21 21:10:53
【问题描述】:

我正在尝试运行具有以下条件的代码:

  1. 使用 MX 记录查找并选择最低优先级(在 MX 中,最低数字是最高优先级)

  2. 如果 MX 不可用或没有响应,请尝试 A 记录

  3. 如果以上都没有,打印不良记录

我已经运行了以下代码:

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")

但我得到一个错误,即使它确实显示了 mx 记录:

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

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

感谢您的帮助

【问题讨论】:

    标签: python dns


    【解决方案1】:

    您正在尝试解析“40 someurl.com.”。请去掉开头的数字和最后的点。您也不是在寻找任何偏好,您只是在选择第一个条目。最后,当不应该为 None 时,您正在检查 None。

    正确的是:

    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')
    

    至少对我来说,是dns.resolver.query 而不是dns.resolver.resolve。请进行调整以使其适合您。

    【讨论】:

      【解决方案2】:

      这是一个简单的逻辑错误。按照你写的方式,如果你得到一个好的 MX 结果(即records != None),那么它会引发一个错误。

      试试这个:

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

      我还将比较从 == 切换到 is 以便更好地练习。见What is the difference between "is None" and "== None"

      【讨论】:

      • 谢谢。当我按照您的建议进行更改并测试域没有 MX,但有 A 记录时 - 我检查第一条记录,而不是移动到第二条记录,我收到以下错误:dns.resolver.NoAnswer: DNS 响应不包含问题的答案:exampledomain.com。在墨西哥
      • @Maskiin 你需要抓住它。见Handling Exceptions - Python Tutorial
      猜你喜欢
      • 1970-01-01
      • 2011-05-19
      • 2017-01-26
      • 2011-08-18
      • 2011-05-16
      • 2013-03-06
      • 2010-12-13
      • 2010-10-08
      • 1970-01-01
      相关资源
      最近更新 更多