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

0 votes
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,470 points
82 views

1 answer to this question.

0 votes

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
• 2,960 points

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,908 views
0 votes
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
• 2,960 points
83 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
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