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

Was it helpful?

Solution

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

OTHER TIPS

You better off just using scapy.

 #! /usr/bin/env python

# Set log level to benefit from Scapy warnings
import logging
logging.getLogger("scapy").setLevel(1)

from scapy.all import *

if __name__ == "__main__":
    hosts   = raw_input('Hostnames you would like to traceroute sepearated by a comma: ')
    ttl     = raw_input("Time To Live: ")
    if not ttl: ttl = 20
    traceroute([x.strip() for x in hosts.split(',')],maxttl=ttl)

Reference : https://gist.github.com/mwatts272/6192900

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top