ADVERTISEMENT
dnspython is a Python library that allows you to perform DNS queries directly from your code. With this library, you can retrieve various DNS records such as IP addresses, mail servers, name servers, and more.
This article explains how to install dnspython and provides a sample script to perform DNS lookups for different types of records.
What is dnspython?
dnspython is a third-party Python library for working with DNS. It supports querying multiple record types, including:
A (IPv4 address)
- AAAA (IPv6 address)
- MX (Mail Exchange)
- NS (Name Server)
- TXT (Text Record)
- SOA (Start of Authority)
Installation
To install dnspython, use the following command:
pip install dnspython
Make sure you’re using Python 3.
Example: DNS Lookup Script
Below is a Python script that performs DNS lookups for several common record types:
#!/usr/bin/env python3
import dns.resolver
import sys
def perform_dns_lookup(domain, record_type='A'):
"""
Perform DNS lookup for a specific domain and record type
"""
try:
resolver = dns.resolver.Resolver()
answers = resolver.resolve(domain, record_type)
print(f"\n{record_type} Records for {domain}:")
print("-" * 50)
for rdata in answers:
if record_type == 'MX':
print(f"Mail Server: {rdata.exchange}, Preference: {rdata.preference}")
else:
print(rdata.to_text())
except dns.resolver.NXDOMAIN:
print(f"Error: Domain {domain} does not exist.")
except dns.resolver.NoAnswer:
print(f"No {record_type} records found for {domain}.")
except Exception as e:
print(f"An error occurred: {str(e)}")
def main():
if len(sys.argv) < 2:
print("Usage: python dns_lookup_example.py <domain>")
print("Example: python dns_lookup_example.py google.com")
sys.exit(1)
domain = sys.argv[1]
record_types = ['A', 'AAAA', 'MX', 'NS', 'TXT', 'SOA']
print(f"Performing DNS lookups for {domain}")
print("=" * 50)
for record_type in record_types:
perform_dns_lookup(domain, record_type)
if __name__ == "__main__":
main()
How to Run the Script
Save the script as dns_lookup_example.py. Run it from the terminal:
python dns_lookup_example.py hanifmu.com
The output will show the DNS records for the specified domain.
dnspython is a powerful tool for developers who need to interact with DNS data. Whether you’re building diagnostic tools, working with domains, or analyzing DNS behavior, this library offers a straightforward and flexible way to query DNS in Python.
ADVERTISEMENT
