create a http server with a trace route in python

To create a HTTP server with a trace route in Python, first import the http.server module and define a new class that extends http.server.BaseHTTPRequestHandler. In the class, override the do_GET method to handle incoming GET requests.

Within the do_GET method, use the subprocess module to run the traceroute command and capture its output. Then, send the output as the response to the client.

Here's an example implementation:

main.py
import http.server
import subprocess

class TraceServer(http.server.BaseHTTPRequestHandler):
    
    def do_GET(self):
        host = self.path[1:] # strip leading slash

        if len(host) == 0:
            self.send_response(400)
            self.end_headers()
            return

        ping_output = subprocess.check_output(['traceroute', '-w', '1', '-q', '1', host])
        
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.end_headers()
        self.wfile.write(ping_output)
537 chars
20 lines

To run the server, instantiate the TraceServer class and use the http.server.HTTPServer to serve it:

main.py
if __name__ == '__main__':
    server_address = ('', 8000)
    httpd = http.server.HTTPServer(server_address, TraceServer)
    httpd.serve_forever()
149 chars
5 lines

This will create a new TraceServer instance listening on port 8000. Whenever a GET request is made to the server with a path representing a valid hostname or IP address, the server will perform a traceroute to that host and return the output as plain text in the HTTP response.

gistlibby LogSnag