Start simple HTTP server with Python
When building new infrastructure elements and deploying servers, quite often you need to test firewall rules before the rest of application stack is deployed. The basic tool of my choice here is curl which is great to testing TCP connections. But it has an important dependency: you actually need to have something listening on the other end of the connection you’re testing. If there’s no software running and servicing the port you specify, you will receive an error.
Traditionally there have been small programs or scripts you’d write - first (many years ago now) in C, later in Perl. They would imply that you have to bring your test code or compiled binary to the server you need to test.
Today I’d like to share a super easy way to start a basic HTTP server with Python - it’s literally just one line that will work in most cases since Python is now ubiqutous enough to be installed by default in most Linux distributions.
You need to use a Python module. It’s a different module for Python 2 and Python 3.
For Python 3, here’s how you start an HTTP server:
In Python 2, you do the same by running a slightly different command:
Both commands can be stopped by the usual Ctrl+C combination.
By just adding a port number to each of the command lines you can make Python run your basic HTTP server on a specific port instead of the default 8000:
Now that you’re learned how to start HTTP server on a specific port, it’s possible to use curl command for testing connectivity to that server.
Here’s how it looks when nothing is running:
And here’s how it looks with HTTP server listening and reponding:
For sake of completeness, here’s how it looks if server or some other firewall between our system and the server is blocking connection using the most typical DROP technique (curl just hangs there until you stop it with Ctrl+C):
That’s all for today. Have fun!