Question

I know this script was discussed here before, but I still can't run it properly. Problem is reading text file line by line. In older script

while host:
  print host  

was used, but using this method program crashed, so I decided to change it to

for host in Open_host:
host = host.strip()

but using this script only gives results of the last line in .txt file. Can someone help me to get it working? The sript below:

# 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()
# loop: excuse trace route for each host
for host in Open_host:
host = host.strip()
# 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() 
Was it helpful?

Solution

I assume you only have two or three hosts in your host.txt file. The culprits are the calls to Open_host.readline() you make before the loop and at the end of each iteration, causing your script to skip the first host in the list, and one host out of two. Just removing those should solve your problem.

Here's the code, updated a bit to be more pythonic:

import subprocess

with open("hostlist.txt", "r") as hostlist, open("results.txt", "a") as output:
    for host in hostlist:
        host = host.strip()

        print "Tracing", host

        trace = subprocess.Popen(["tracert", "-w", "100", host], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        while True:
            hop = trace.stdout.readline()

            if not hop: break

            print '-->', hop.strip()
            output.write(hop)

        # When you pipe stdout, the doc recommends that you use .communicate()
        # instead of wait()
        # see: http://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait
        trace.communicate()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top