Search

M y    b r a i n    h u r t s  !                                           w e                 r e a l l y                 t h i n k                   w h a t                y o u             k n o w

13 July 2016

Simple webserver with twisted

The Python oneliner webserver python -m SimpleHTTPServer (for Python 2.x) or python -m http.server (for Python 3.x) is useful in many scenarios, but sometimes it simply does not cut it because it is meant for development only, is not secure, and is single-threaded.

A better oneline webserver comes with Twisted, the library that the original bittorrent reference implementation was written in.
Installing twisted for the current user only:

pip install twisted --user

Installing twisted system-wide:

sudo pip install twisted

Once installed you can run the default twisted webserver with a command like twistd -n web --path . where the dot represents the current folder. Replace with an absolute path if you need.

The version below additionally displays the internal and external IP addresses, so that you can launch the server and instantly connect to it by entering the displayed IP on your mobile devices or another computers on your local network.

PORT=8080
echo "Local: http://localhost:$PORT"
echo 'LAN:   http://'$(ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'):$PORT
echo 'WAN:   http://'$(wget http://ipinfo.io/ip -qO -):$PORT
twistd -n web --listen "tcp:$PORT:interface=0.0.0.0" --path /var/www/html
To see all the custom options such as binding to a custom IP and port:
twistd web --help

If the --listen is omitted by default port 8080 with bind IP 0.0.0.0 — this will make the server visible to the entire LAN.

For example, to only expose the server on the local machine at http://localhost:7777 use:

twistd -n web --listen "tcp:7777:interface=127.0.0.1" --path /var/www/html

In order to be able to connect via the external IP you'll need to set up port forwarding on your router, for example, as described at www.noip.com/support/knowledgebase/general-port-forwarding-guide.