Python Script for Traceroute and printing the output in file shows error( OSError: [Errno 2] No such file or directory) in Linux Mint

linuxnetworkingpythonsubprocesstraceroute

I am trying to perform traceroute on google.com using python script and write the output to a file ie output.txt

If I directly use subprocess.call('traceroute','google.com') it works perfectly fine and the output gets printed on the screen. Since I want to get the output in a file, I am using

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

and then writing the pipe data to file. However I get an error in this line
i.e. OSError: [Errno 2] No such file or directory

Code :

import urllib
import time 
import datetime, threading
from bs4 import BeautifulSoup
import urllib2
import subprocess
import socket


fp2=open("output.txt",'w')


#This function will be executed after every x minutes


def TraceRoute():



        hostname="google.com"
        fp2.write(hostname+"    :   ")
        print(hostname)

        #subprocess.call(['traceroute',hostname])

        traceroute = subprocess.Popen(["tracert", '-w', '100',          hostname],stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        while (True):
                hop = traceroute.stdout.readline()
                if not hop: break
                print '-->',hop
                fp2.write( hop )


        threading.Timer(60*50, TraceRoute).start() #Ensures periodic execution of TraceRoute( ) x=60*50 seconds

TraceRoute()    

Error :

Traceback (most recent call last):

File "./scr3.py", line 87, in
TraceRoute()

File "./scr3.py", line 76, in TraceRoute
traceroute = subprocess.Popen(["tracert", '-w', '100', hostname],stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
File "/usr/lib/python2.7/subprocess.py", line 710, in init
errread, errwrite)

File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception

OSError: [Errno 2] No such file or directory

How to resolve this ? I am stuck on this since forever. Please help

Best Answer

Pretty sure it should be traceroute not tracert. tracert is a windows command , you can also use iter and stdout.readline to read the output:

traceroute = subprocess.Popen(["traceroute", '-w', '100',hostname],stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

for line in iter(traceroute.stdout.readline,""):
    print(line)
Related Topic