Can you show me an example of using DNS dig commands in a Python script

+1 vote
I'm trying to incorporate DNS queries into a Python script for a project involving network security analysis. I’ve been using the dig command from the terminal to retrieve DNS records, but I’d like to automate this process through Python.

How can I use the subprocess module to run dig commands within my Python script and then parse the output for further analysis? If there’s a more Pythonic way to perform DNS queries (without shelling out to dig), I’d love to see an example of that as well!
Oct 17 in Cyber Security & Ethical Hacking by Anupam
• 3,890 points
92 views

1 answer to this question.

+1 vote

You can run shell commands like dig from within a Python script using the subprocess module.

import subprocess

def dig_query(domain):
    result = subprocess.run(['dig', domain, '+short'], stdout=subprocess.PIPE)
    return result.stdout.decode('utf-8')

domain = 'example.com'
output = dig_query(domain)
print(output)

Rather than using subprocess, you can use Python libraries like dnspython to perform DNS queries directly:

import dns.resolver

def query_dns(domain):
    result = dns.resolver.resolve(domain, 'A')
    for ipval in result:
        print('IP:', ipval.to_text())

query_dns('example.com')
answered Oct 21 by CaLLmeDaDDY
• 3,320 points
Great examples! I’m curious—when would you recommend using subprocess with dig over a library like dnspython? Are there specific use cases where one is better than the other?

Related Questions In Cyber Security & Ethical Hacking

+1 vote
0 answers

How can I encryption/decryption in Rijndael using python

I found this https://github.com/moeenz/rijndael ,but does not ...READ MORE

Sep 28, 2019 in Cyber Security & Ethical Hacking by Ahmed
• 310 points
4,918 views
+1 vote
1 answer

How do you decrypt a ROT13 encryption on the terminal itself?

Yes, it's possible to decrypt a ROT13 ...READ MORE

answered Oct 17 in Cyber Security & Ethical Hacking by CaLLmeDaDDY
• 3,320 points
97 views
+1 vote
1 answer
+1 vote
1 answer
+1 vote
1 answer
+1 vote
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP