Search code examples
pythonnslookupdig

Command Line Arguments in DNSlookup


I'm trying to check reverse lookup of IP address and then write the result to txt file. But I don't know how can I get the IP address as command line argument (Linux environment) instead of write the IP inside the script.

My script:

import sys, os, re, shlex, urllib, subprocess 

cmd='dig' -x 8.8.8.8 @192.1.1.1

proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
out, err = proc.communicate()

sys.stdout = open("/tmp/test.txt", "w")
print(out)
sys.stdout.close()

Solution

  • You can get cli arguments with sys.argv:

    import sys, subprocess 
    
    cmd = 'dig -x %s @192.1.1.1' % sys.argv[1]
    
    proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    out, err = proc.communicate()
    
    with open("/tmp/test.txt", "w+") as f:
        f.write(out)