Skip to content

Python 3: http.server for quick file transfers

Last updated on 2019-04-06

A quick look

Python 3 has a module called http.server that can be used as a quick – and insecure – way to download files from a particular host.

To do so, simply run:

python3 -m http.server 8888

Replace 8888 with your port of choice.

Keep in mind that this provides:

  • NO authentication: anyone can access the host on the specified port
  • NO confidentiality: a man-in-the-middle can read all traffic
  • NO integrity: a man-in-the-middle can modify all traffic

And as such, is only suitable for brief usage, and when scp isn’t an option.

Visiting http://<host_ip>:8888 will give you a list of files present in the directory where the command was executed, allowing you to easily download them.

To stop the http.server instance you just created, simply hit Ctrl+C.

A deeper look

The meaning behind python3 -m can be found with python3 --help:

-m mod : run library module as a script (terminates option list)

Where mod is a Python module; in this case, http.server.

The usage of http.server is explained as such:

http.server can also be invoked directly using the -m switch of the interpreter with a port number argument. Similar to the previous example, this serves files relative to the current directory:
python -m http.server 8000
By default, server binds itself to all interfaces. The option -b/--bind specifies a specific address to which it should bind. For example, the following command causes the server to bind to localhost only:
python -m http.server 8000 --bind 127.0.0.1
New in version 3.4: --bind argument was introduced.
By default, server uses the current directory. The option -d/--directory specifies a directory to which it should serve the files. For example, the following command uses a specific directory:
python -m http.server --directory /tmp/
New in version 3.7: --directory specify alternate directory

Source: https://docs.python.org/3/library/http.server.html

Example

We have 2 virtual machines configured to use the same host-only network, meaning:

  • They can communicate with the host system
  • They can communicate with each other

We have a file in machine A that we want to transfer to machine B.

In machine A:

python3 -m http.server -b 172.28.128.4 8888

In machine B:

wget http://172.28.128.4:8888/my_file.txt

A brief note: this example isn’t particularly OS-specific. Python can be installed on Windows/macOS as well, and wget also exists for both. Using a browser works just fine too.

Python 2

If Python 3 is not available, the same can be achieved in Python 2 with the following command:

python -m SimpleHTTPServer 8888

Python 2 does not offer the -b/--bind or --directory options. For more details, see https://docs.python.org/2/library/simplehttpserver.html.

Published inUncategorized