Search code examples
pythoncommand-linenslookup

Get nslookup Results in Windows 7 Cmd Prompt


I'm trying to do an nslookup with a list of IP addresses. I'm doing the nslookup on a Windows 7 machine. The error I'm getting is that when I run the nslookup, I get the variable result back as a zero every time. How do I get

   Server: server.address.com
   Address: 10.45.66.77

   Server: server.address.com
   Address: 108.36.85.35

as my result instead of 0?

#!/usr/bin/env python

#purpose of script: To conduct an nslookup on a list of IP addresses

import os, csv

#get list of IP's from file
inFile='filelocation/Book1.txt'
ipList = []
with open(inFile, 'rb') as fi:
    for line in fi: 
        line = line.replace(',', '')#remove commas and \n from list
        line = line.replace('\r', '')
        line = line.replace('\n', '')
        ipList.append(line)# create list of IP addresses to lookup

#output results
outFile='filelocation/outFile.txt'
fo = open(outFile, 'w')
for e in ipList:
    result = str(os.system('nslookup ' + e))#send nsLookup command to cmd prompt. Result = 0 everytime
    fo.write(result)

Solution

  • os.system doesn't return the output of the command that you run; it prints it instead.

    To run a command and get its output, use os.popen(...).read() instead:

    result = os.popen('nslookup ' + e).read()