Wednesday, July 9, 2014

Single Line Web Server in Python

This is an old trick, but very useful for transferring files in a pinch - especially in cross platform situations. Also great if you need a simple web server for testing.

The commands are simple.

For Python 2.x: python -m SimpleHTTPServer
[user@fedora folder1]$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
For Python 3.x: python3 -m http.server
[user@fedora folder1]$ python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 ...
Both of these default to port 8000, but you can add a port number to the end of the line to specify something else if you like. The current directory is used as the root folder. If an index.html or index.htm file is present it will be served initially, otherwise the server will provide a directory listing. Just point your browser to the system:
http://<your-ip-address>:8000
Make sure your firewall/IP-tables are properly adjusted to allow the inbound connection.

The terminal will show a running Apache style access log of connections. CTRL + c to exit.

Performance is pretty good too:



Official documentation here:
https://docs.python.org/2/library/simplehttpserver.html
https://docs.python.org/3/library/http.server.html