Python Simple Http(s) Server

最近为了在局域网中传输文件,用Python搭建了一个很简单的 HTTP web server to serve files, 其实有其他软件也可以完成类似功能,甚至scp command也行。不过这个简单的HTTP web server里面的 文件结构一目了然,下载非常方便。

后续还可以添加basic auth service, 甚至SSL/TLS support, 作为其他服务的测试工具。

How to:

  1. virtualenvwrapper 先搭建一个python3 项目和对应的环境。
  2. 激活环境后, 写一个shell script,输出运行时的网址和端口

比如在Mac中,使用如下脚本:

1
2
3
4
5
6
7
8
9
#!/bin/bash

# Use the output in browser in another machine
echo "$(ifconfig | grep -A 10 ^en0 | grep inet | grep -v inet6 | cut -d" " -f2)":8000

# Launch the server
# port number: 8000
# --directory: old version python may not support this option
python3 -m http.server 8000 --bind 0.0.0.0 --directory <absolute path to share folder>

Basic Auth

https://gist.github.com/fxsjy/5465353 You can package it in container or run on virtualenv.

1
2
3
4
# Works with python2
# port: 8080
# auth: user:password
python2 -m main.py 8080 chengdol:123456

HTTPS Basic Auth

https://github.com/tianhuil/SimpleHTTPAuthServer You can run the pip in python2 virtualenv or build a docker container.

Modify to build a image with https auth server, for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# works on python2
FROM python:2

WORKDIR /usr/src/app

USER root
# pip install
RUN pip install SimpleHTTPAuthServer
# to setup self-signed certificate, need to pre-generated key and cert
RUN mkdir -p /root/.ssh
# From source code it use .ssh folder to store the pem.
RUN openssl req \
-newkey rsa:2048 -new -nodes -x509 -days 3650 \
-keyout /root/.ssh/key.pem -out /root/.ssh/cert.pem \
-subj "/C=US/ST=CA/L=San Jose/O=GOOG/OU=Org/CN=localhost"

# copy other files to WORKDIR
COPY file.txt .

EXPOSE 8080
# start with https
CMD ["python", "-m", "SimpleHTTPAuthServer", "8080", "chengdol:123456", "--https"]

Then go to firefox, type and hit https://localhost:8080.

0%