Python DNS Server IP Address Query

耗尽温柔 提交于 2019-12-11 04:35:08

问题


I am trying to get the DNS Server IP Addresses using python. To do this in Windows command prompt, I would use

ipconfig -all

As shown below:

I want to do the exact same thing using a python script. 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.


回答1:


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:

#!/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/4017219

Edit: If anyone has a better way of doing this please share :)



来源:https://stackoverflow.com/questions/50015586/python-dns-server-ip-address-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!