Python (Scripting) - nslookup
by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
nslookup can be used to perform DNS lookup.
pip install nslookup
Here is an example of how to use nslookup.
#!/usr/bin/python3
from nslookup import Nslookup
dns_query = Nslookup()
hostname = "server1.example.com"
result = dns_query.dns_lookup(hostname)
print(f"full response = {result.response_full}")
print(f"answer = {result.answer}")
Which should return something like this.
full response = server1.example.com. 10800 IN A 10.11.12.13
answer = 10.11.12.13
Almost always, it makes sense to include an if statement to print a message if nslookup fails to resolve the hostname to an IP address.
#!/usr/bin/python3
from nslookup import Nslookup
dns_query = Nslookup()
hostname = "server1.example.com"
result = dns_query.dns_lookup(hostname)
if (len(result.response_full) == 0):
print(f"nslookup failed to resolve {domain} to an IP address")
sys.exit(1)
print(f"full response = {result.response_full}")
print(f"answer = {result.answer}")
Did you find this article helpful?
If so, consider buying me a coffee over at