【问题标题】:Python DNS Server IP Address QueryPython DNS 服务器 IP 地址查询
【发布时间】:2018-04-25 06:39:57
【问题描述】:

我正在尝试使用 python 获取 DNS 服务器 IP 地址。要在 Windows 命令提示符下执行此操作,我会使用

ipconfig -all

如下图:

我想使用 python 脚本做同样的事情。有没有办法提取这些值? 我成功提取了设备的 IP 地址,但 DNS 服务器 IP 被证明更具挑战性。

【问题讨论】:

  • 可以使用子进程模块调用命令并接收其输出
  • @Drako 去 shell 应该是最后的资源,因为它有很多缺点。而是尝试找到一个 Python 库来让您访问 Windows 主机配置详细信息。
  • 有点同意@PatrickMevzek - 取决于项目的大小以及它是否是您唯一需要的东西,等等。

标签: python bash cmd dns


【解决方案1】:

DNS Python (dnspython) 可能会有所帮助。您可以通过以下方式获取 DNS 服务器地址:

 import dns.resolver
 dns_resolver = dns.resolver.Resolver()
 dns_resolver.nameservers[0]

【讨论】:

    【解决方案2】:

    我最近不得不获取一组跨平台主机(linux、macOS、windows)使用的 DNS 服务器的 IP 地址,这就是我最终这样做的方式,我希望它会有所帮助:

    #!/usr/bin/env python
    
    import platform
    import socket
    import subprocess
    
    
    def is_valid_ipv4_address(address):
        try:
            socket.inet_pton(socket.AF_INET, address)
        except AttributeError:  # no inet_pton here, sorry
            try:
                socket.inet_aton(address)
            except socket.error:
                return False
            return address.count('.') == 3
        except socket.error:  # not a valid address
            return False
    
        return True
    
    
    def get_unix_dns_ips():
        dns_ips = []
    
        with open('/etc/resolv.conf') as fp:
            for cnt, line in enumerate(fp):
                columns = line.split()
                if columns[0] == 'nameserver':
                    ip = columns[1:][0]
                    if is_valid_ipv4_address(ip):
                        dns_ips.append(ip)
    
        return dns_ips
    
    
    def get_windows_dns_ips():
        output = subprocess.check_output(["ipconfig", "-all"])
        ipconfig_all_list = output.split('\n')
    
        dns_ips = []
        for i in range(0, len(ipconfig_all_list)):
            if "DNS Servers" in ipconfig_all_list[i]:
                # get the first dns server ip
                first_ip = ipconfig_all_list[i].split(":")[1].strip()
                if not is_valid_ipv4_address(first_ip):
                    continue
                dns_ips.append(first_ip)
                # get all other dns server ips if they exist
                k = i+1
                while k < len(ipconfig_all_list) and ":" not in ipconfig_all_list[k]:
                    ip = ipconfig_all_list[k].strip()
                    if is_valid_ipv4_address(ip):
                        dns_ips.append(ip)
                    k += 1
                # at this point we're done
                break
        return dns_ips
    
    
    def main():
    
        dns_ips = []
    
        if platform.system() == 'Windows':
            dns_ips = get_windows_dns_ips()
        elif platform.system() == 'Darwin':
            dns_ips = get_unix_dns_ips()
        elif platform.system() == 'Linux':
            dns_ips = get_unix_dns_ips()
        else:
            print("unsupported platform: {0}".format(platform.system()))
    
        print(dns_ips)
        return
    
    
    if __name__ == "__main__":
        main()
    

    我用来制作这个脚本的资源:

    https://stackoverflow.com/a/1325603

    https://stackoverflow.com/a/4017219

    编辑:如果有人有更好的方法,请分享:)

    【讨论】:

      猜你喜欢
      • 2016-09-11
      • 1970-01-01
      • 2021-08-25
      • 2013-05-18
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      相关资源
      最近更新 更多