在 Python 中获取本地 DNS 设置

Get local DNS settings in Python

是否有任何优雅的跨平台 (Python) 方法来获取本地 DNS 设置?

它可能与复杂的模块组合一起工作,例如 platformsubprocess,但也许已经有一个好的模块,例如 netifaces 可以在低级别并节省一些 "reinventing the wheel" 精力。

不太理想,人们可能会查询类似 dig 的内容,但我发现它 "noisy",因为它会 运行 一个额外的请求,而不是仅仅检索本地已经存在的东西.

有什么想法吗?

使用子进程,您可以在 MacBook 或 Linux 系统中执行类似的操作

import subprocess

process = subprocess.Popen(['cat', '/etc/resolv.conf'],
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print(stdout, stderr)

或者做这样的事情

import subprocess
with open('dns.txt', 'w') as f:
    process = subprocess.Popen(['cat', '/etc/resolv.conf'], stdout=f)

第一个输出将转到标准输出,第二个输出到文件

也许这个可以解决您的问题

import subprocess

def get_local_dns(cmd_):
    with open('dns1.txt', 'w+') as f:
        with open('dns_log1.txt', 'w+') as flog:
            try:
                process = subprocess.Popen(cmd_, stdout=f, stderr=flog)
            except FileNotFoundError as e:
                flog.write(f"Error while executing this command {str(e)}")


linux_cmd = ['cat', '/etc/resolv.conf']
windows_cmd = ['windows_command', 'parameters']
commands = [linux_cmd, windows_cmd]


if __name__ == "__main__":
    for cmd in commands:
        get_local_dns(cmd)

谢谢@MasterOfTheHouse。 我最终编写了自己的函数。它不是那么优雅,但它现在可以完成工作。有很大的改进空间,但是...

import os
import subprocess

def get_dns_settings()->dict:
    # Initialize the output variables
    dns_ns, dns_search = [], ''

    # For Unix based OSs
    if os.path.isfile('/etc/resolv.conf'):
        for line in open('/etc/resolv.conf','r'):
            if line.strip().startswith('nameserver'):
                nameserver = line.split()[1].strip()
                dns_ns.append(nameserver)
            elif line.strip().startswith('search'):
                search = line.split()[1].strip()
                dns_search = search

    # If it is not a Unix based OS, try "the Windows way"
    elif os.name == 'nt':
        cmd = 'ipconfig /all'
        raw_ipconfig = subprocess.check_output(cmd)
        # Convert the bytes into a string
        ipconfig_str = raw_ipconfig.decode('cp850')
        # Convert the string into a list of lines
        ipconfig_lines = ipconfig_str.split('\n')

        for n in range(len(ipconfig_lines)):
            line = ipconfig_lines[n]
            # Parse nameserver in current line and next ones
            if line.strip().startswith('DNS-Server'):
                nameserver = ':'.join(line.split(':')[1:]).strip()
                dns_ns.append(nameserver)
                next_line = ipconfig_lines[n+1]
                # If there's too much blank at the beginning, assume we have
                # another nameserver on the next line
                if len(next_line) - len(next_line.strip()) > 10:
                    dns_ns.append(next_line.strip())
                    next_next_line = ipconfig_lines[n+2]
                    if len(next_next_line) - len(next_next_line.strip()) > 10:
                        dns_ns.append(next_next_line.strip())

            elif line.strip().startswith('DNS-Suffix'):
                dns_search = line.split(':')[1].strip()

    return {'nameservers': dns_ns, 'search': dns_search}

print(get_dns_settings())

顺便问一下...您是如何用同一个帐户写出两个答案的?