简体   繁体   English

Python DNS 服务器 IP 地址查询

[英]Python DNS Server IP Address Query

I am trying to get the DNS Server IP Addresses using python.我正在尝试使用 python 获取 DNS 服务器 IP 地址。 To do this in Windows command prompt, I would use要在 Windows 命令提示符下执行此操作,我将使用

ipconfig -all ipconfig -all

As shown below:如下所示:

在此处输入图片说明

I want to do the exact same thing using a python script.我想使用 python 脚本做完全相同的事情。 Is there any way to extract these values?有没有办法提取这些值? I was successful in extracting the IP address of my device, but DNS Server IP is proving to be more challenging.我成功提取了设备的 IP 地址,但事实证明 DNS 服务器 IP 更具挑战性。

DNS Python ( dnspython ) might be helpful. DNS Python ( dnspython ) 可能会有所帮助。 You can get the DNS server address with:您可以通过以下方式获取 DNS 服务器地址:

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

I recently had to get the IP addresses of the DNS servers that a set of cross platform hosts were using (linux, macOS, windows), this is how I ended up doing it and I hope it's helpful:我最近不得不获取一组跨平台主机正在使用的 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()

Resources I used to make this script:我用来制作这个脚本的资源:

https://stackoverflow.com/a/1325603 https://stackoverflow.com/a/1325603

https://stackoverflow.com/a/4017219 https://stackoverflow.com/a/4017219

Edit: If anyone has a better way of doing this please share :)编辑:如果有人有更好的方法,请分享:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM