欢迎访问宙启技术站
智能推送

使用Python中的whois()函数获取域名的DNS解析记录

发布时间:2024-01-13 05:37:17

To retrieve the DNS resolution records of a domain using the whois() function in Python, you can take advantage of the python-whois library. This library allows you to perform WHOIS queries to retrieve information about domain registrations.

To install the python-whois library, you can use the following command:

pip install python-whois

Once installed, you can use the whois() function to retrieve the DNS resolution records. Here's an example:

import whois

def get_dns_records(domain):
    try:
        record = whois.whois(domain)
        
        if record is not None:
            if isinstance(record.name_servers, list):
                return record.name_servers
            else:
                return [record.name_servers]
            
    except whois.parser.PywhoisError as e:
        print(f"Error: {e}")
    
    return []

domain = "example.com"
dns_records = get_dns_records(domain)
print(dns_records)

In this example, we define a function get_dns_records() that takes a domain name as an input. Inside the function, we use the whois() function from the python-whois library to retrieve the WHOIS record for the specified domain.

We check if the retrieved record is not None. If it's not None, we retrieve the name servers associated with the domain using the name_servers attribute of the record. The name_servers attribute can either be a string or a list of strings, so we handle both cases accordingly.

Finally, we return the list of name servers associated with the domain. If any error occurs during the retrieval process, we catch the PywhoisError exception and print the error message.

In the main part of the code, we specify the domain for which we want to retrieve the DNS resolution records (in this case, "example.com"). We then call the get_dns_records() function with the domain as an argument and store the result in the dns_records variable.

Finally, we print the retrieved DNS resolution records.

Note: Retrieving DNS resolution records using the WHOIS protocol may not always provide complete or up-to-date information. It's recommended to use other DNS-related libraries or tools, such as dnspython, for more accurate and detailed DNS-related queries.