Search code examples
pythonpython-3.xnslookup

How to select specific text from the output?


I am doing nslookup by reading hostname from one csv file and I want to write the FQDN into the another csv file.

This is my code:

import subprocess

with open('csv1.csv', 'r') as i, open('csv2.csv', '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')

The problem I am facing that it gives all detailed information similarly when done in cmd->nslookup, like the 'SERVER', 'ADDRESS', 'FQDN' and it's IP ADDRESS Here is the example of one of the hostname:

(b'Server:  anything.na.com\r\nAddress:  10.3.56.7\r\n\r\nName:    ABCD12.na.com\r\nAddress:  10.4.67.8\r\nAliases:  abcd12.na.com\r\n\r\n'

I only want to extract FQDN name here into the csv file.


Solution

  • Just find the data you are looking for, using reor split:

    import subprocess
    
    with open('csv1.csv', 'r') as i, open('csv2.csv', '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)
            stdout_data, stderr_data = proc.communicate(0)
            fqdn = stdout_data.split(b'Server:  ')[1].split(b'\r\n')[0]
            o.write('{}\n'.format(fqdn))