traceroute multiple hosts in python
Question: I'm writing a script to do traceroute for a list of hostnames. what I'm trying
to do is reading hostname from a text file, line by line, performing tracert
for each host using subprocess and writing the result in another file. here is
my code

    
    
        # import subprocess
        import subprocess
        # Prepare host and results file
        Open_host = open('c:/OSN/host.txt','r')
        Write_results = open('c:/OSN/TracerouteResults.txt','a')
        host = Open_host.readline()
        # while loop: excuse trace route for each host
        while host:
           print host
        # execute Traceroute process and pipe the result to a string 
           Traceroute = subprocess.Popen(["tracert", '-w', '100', host],  
         stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
           while True:    
               hop = Traceroute.stdout.readline()
               if not hop: break
               print '-->',hop
               Write_results.write( hop )
           Traceroute.wait()  
        # Reading a new host   
           host = Open_host.readline()
        # close files
        Open_host.close()
        Write_results.close() 
    

My problem is that this script works only for a host file with 1 hostname (or
1 line). when host file contain multiple line, for example: hostname1.com
hostname2.com hostname3.com It will give me this notice for the 1st two line

"Unable to resolve target system name hostname1.com"

"Unable to resolve target system name hostname2.com"

And only give tracert result for the last line.

I'm not sure what's wrong with my script, please help me to fix it. Thanks a
lot.

Steven


Answer: Try `host = host.strip()` before making the call; tracert seems to be choking
on the newlines.

