Python DNS服务器IP地址查询

Abh*_*ran 3 python dns bash cmd

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

ipconfig-全部

如下所示:

在此输入图像描述

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

小智 7

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

 import dns.resolver
 dns_resolver = dns.resolver.Resolver()
 dns_resolver.nameservers[0]
Run Code Online (Sandbox Code Playgroud)


Mav*_*ick 5

最近,我必须获取一组跨平台主机(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()
Run Code Online (Sandbox Code Playgroud)

我用来制作此脚本的资源:

/sf/answers/92792241/

/sf/answers/281205361/

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