Python DNS 服务器 IP 地址查询

3
我想使用Python获取DNS服务器IP地址。要在Windows命令提示符中执行此操作,我会使用:

ipconfig -all

如下所示:

enter image description here

我想使用Python脚本做完全相同的事情。有没有办法提取这些值? 我已经成功提取了我的设备的IP地址,但是DNS服务器IP正在变得更具挑战性。

可以使用subprocess模块调用命令并接收其输出。 - Drako
@Drako 去使用 shell 应该是最后的选择,因为它有很多缺点。相反,尝试找到一个 Python 库,可以让你访问 Windows 主机配置细节。 - Patrick Mevzek
有些同意@PatrickMevzek-这取决于项目的规模以及它是否是您需要的唯一东西等。 - Drako
2个回答

7

DNS Python(dnspython)可能会有所帮助。您可以使用以下命令获取DNS服务器地址:

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

5

最近我需要获取一组跨平台主机正在使用的DNS服务器的IP地址(linux、macOS、windows),以下是我如何实现的,希望能对你有所帮助:

#!/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://dev59.com/lXM_5IYBdhLWcg3wjj-r#1325603

https://dev59.com/I3RC5IYBdhLWcg3wXP0C#4017219

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接