Python Dns Record Lookup Utility

Written by

in

When it comes to troubleshooting network issues, verifying DNS records is one of the first steps every sysadmin or developer takes. While there are plenty of online tools that can fetch A, MX, TXT, and other DNS records, having a Python DNS record lookup utility at your fingertips gives you the flexibility to automate checks, integrate them into CI pipelines, or simply avoid the hassle of opening a browser. In this guide we’ll walk through why DNS lookups matter, explore the most popular Python libraries, and build a lightweight, extensible command‑line utility that can query any record type with just a few lines of code.

Why a Dedicated DNS Lookup Tool in Python?

Even though the nslookup and dig commands are powerful, they have a few limitations that a Python‑based solution can overcome:

  • Automation: Scripted lookups can be scheduled, logged, and combined with other monitoring tools.
  • Cross‑platform consistency: The same code works on Linux, macOS, and Windows without relying on external binaries.
  • Extensibility: You can parse results, trigger alerts, or feed data into dashboards directly from Python.
  • Integration: Use the results in web applications, Flask APIs, or Jupyter notebooks for real‑time diagnostics.

Choosing the Right Library

Python offers several ways to perform DNS queries. Below is a quick comparison of the most common options:

1. socket (built‑in)

  • Pros: No external dependencies, simple for basic A/AAAA lookups.
  • Cons: Limited to IP address resolution; cannot query MX, TXT, SRV, etc.

2. dns.resolver from dnspython

  • Pros: Full support for all DNS record types, asynchronous API, robust error handling.
  • Cons: Requires installing a third‑party package (pip install dnspython).

3. requests + public DNS‑over‑HTTPS (DoH) services

  • Pros: Bypasses local resolver, useful for testing external DNS behavior.
  • Cons: Dependent on internet connectivity and third‑party APIs.

For a versatile command‑line utility we’ll focus on dnspython because it provides the most comprehensive feature set while remaining easy to install.

Setting Up the Environment

First, ensure you have Python 3.8+ installed. Then install dnspython:

pip install dnspython

Optionally, you can create a virtual environment to keep dependencies isolated:

python -m venv dns-env
source dns-env/bin/activate  # On Windows: dns-env\Scripts\activate
pip install dnspython

Building the Core Lookup Function

The following function abstracts the DNS query logic. It accepts a domain name and a record type (e.g., A, MX, TXT) and returns a list of human‑readable results.

import dns.resolver
from typing import List

def dns_lookup(host: str, record_type: str = "A") -> List[str]:
    """
    Perform a DNS query for the given host and record type.
    
    Args:
        host: Domain name to query (e.g., 'example.com')
        record_type: DNS record type (A, AAAA, MX, TXT, CNAME, NS, SRV, etc.)
    
    Returns:
        A list of strings representing the answer section.
    """
    try:
        answers = dns.resolver.resolve(host, record_type, raise_on_no_answer=False)
        results = []
        for rdata in answers:
            if record_type.upper() == "MX":
                # MX records have preference and exchange
                results.append(f"{rdata.preference} {rdata.exchange}")
            elif record_type.upper() == "SOA":
                results.append(str(rdata.mname))
            else:
                results.append(str(rdata))
        return results
    except dns.resolver.NXDOMAIN:
        return [f"Error: {host} does not exist (NXDOMAIN)"]
    except dns.resolver.NoAnswer:
        return [f"Error: No {record_type} record found for {host}"]
    except dns.exception.DNSException as e:
        return [f"DNS query failed: {e}"]

Command‑Line Interface (CLI) with argparse

To make the utility user‑friendly, we’ll wrap the lookup function in a simple CLI using argparse. This allows users to specify the target domain and optionally the record type.

import argparse

def main():
    parser = argparse.ArgumentParser(
        description="Python DNS record lookup utility – query any DNS record type."
    )
    parser.add_argument("domain", help="Domain name to query (e.g., example.com)")
    parser.add_argument(
        "-t", "--type",
        default="A",
        help="DNS record type (A, AAAA, MX, TXT, CNAME, NS, SRV, SOA, etc.)"
    )
    args = parser.parse_args()

    results = dns_lookup(args.domain, args.type.upper())
    print(f"\n{args.type.upper()} records for {args.domain}:")
    for line in results:
        print(f"  - {line}")

if __name__ == "__main__":
    main()

Save the script as dnslookup.py, make it executable (chmod +x dnslookup.py on Unix), and run examples like:

  • python dnslookup.py example.com -t A
  • python dnslookup.py gmail.com -t MX
  • python dnslookup.py cloudflare.com -t TXT

Advanced Features You Can Add

Once the basic utility is in place, consider extending it with one or more of the following enhancements to turn it into a full‑featured DNS toolbox:

  1. Parallel queries: Use concurrent.futures.ThreadPoolExecutor to resolve multiple domains at once, speeding up bulk checks.
  2. Custom DNS resolvers: Allow users to specify a DNS server IP (e.g., 8.8.8.8) via a --resolver flag.
  3. JSON output: Add a --json switch that prints results in machine‑readable format for integration with monitoring systems.
  4. DNSSEC validation: Leverage dnspython’s DNSSEC support to verify signed records.
  5. DoH fallback: If the local resolver fails, automatically query a DNS‑over‑HTTPS endpoint like Cloudflare’s https://cloudflare-dns.com/dns-query.

Testing and Debugging Tips

Reliable DNS tools need thorough testing. Here are some practical suggestions:

  • Use pytest with parametrized tests for multiple domains and record types.
  • Mock dns.resolver.resolve using unittest.mock to simulate NXDOMAIN, timeout, and empty answer scenarios.
  • Run the script against known public domains (e.g., example.com for A, google.com for MX) to verify correctness.
  • Check for IPv6 compatibility by querying AAAA records on both IPv4‑only and dual‑stack networks.

SEO‑Friendly Summary

If you’re searching for a Python DNS record lookup utility, the combination of dnspython and a concise CLI script offers a powerful, cross‑platform solution. It covers all major record types, handles errors gracefully, and can be expanded with features like parallel processing, custom resolvers, and JSON output. By integrating this utility into your development workflow, you gain instant visibility into DNS configurations, reduce reliance on external web tools, and empower automated monitoring pipelines.

Conclusion

Building a Python DNS lookup tool is a rewarding exercise that blends networking fundamentals with practical scripting. Whether you need a quick one‑off query or a scalable component for continuous health checks, the code snippets above provide a solid foundation. Install dnspython, customize the CLI to your needs, and you’ll have a reliable, SEO‑optimized utility that keeps your DNS diagnostics fast, accurate, and fully under your control.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *