Search code examples
pythonpython-2.7csvnslookup

I have list of adresses which i need to nslookup and send to csv


I am trying to do nslookup for addresses in my adrese.txt file and I would like to save them as .csv. Currently my biggest problem is that it only does nslookup for only one address and not all. It just exits with 0 and in my file there is only one adress. I am new to python and got no idea how to fix it. Also replacing .txt with csv in output file would be nice too.

edit: adress getting from text file works, second part is the problem, don't know why

import subprocess

f = open("adrese.txt")
next = f.read()
ip=[]

while next != "":
  ip.append(next)
  next = f.read()
file_ = open('nslookup.txt', 'w')
for i in ip:
  process = subprocess.Popen(["nslookup", i], stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
  output = process.communicate()[0]
  file_.write(output)
file_.close()

Solution

  • The reason why its doing this is because while next != "" is not doing what you want it to.

    Instead, consider this:

    import subprocess
    
    with open('adrese.txt') as i, open('nslookup.txt', 'w') as o:
       for line in i:
         if line.strip(): # skips empty lines
            proc = subprocess.Popen(["nslookup", line.strip()],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            o.write('{}\n'.format(proc.communicate()[0]))
    
    print('Done')