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.py537 chars20 lines
To run the server, instantiate the TraceServer
class and use the http.server.HTTPServer
to serve it:
main.py149 chars5 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