Abhishek
Abhishek

Reputation: 380

Python DNS Server IP Address Query

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:

enter image description here

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.

Upvotes: 3

Views: 15279

Answers (2)

Kevin Moore
Kevin Moore

Reputation: 81

DNS Python (dnspython) might be helpful. You can get the DNS server address with:

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

Upvotes: 8

Maverick
Maverick

Reputation: 711

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 :)

Upvotes: 5

Related Questions