0%

快速搭建HTTPS下载服务

项目中可能会遇到需要临时搭建一个http下载服务,用于内网分享一些文件数据。除了使用Nginx等通用方式搭建下载服务之外,可以使用python快速搭建http下载服务。

搭建http下载服务

使用cd命令将当前目录切换到待分享文件所在目录,之后运行如下命令,即可使用http访问到当前目录下的所有文件。

1
python -m SimpleHTTPServer 端口号

这里介绍一下,SimpleHTTPServer是python内集成的一个module,-m 表示运行指定的module。

搭建https下载服务

编写python脚本程序

python 3.x

1
2
3
4
5
6
7
8
9
10
from http.server import HTTPServer, BaseHTTPRequestHandler
import ssl

httpd = HTTPServer(('localhost', 443), BaseHTTPRequestHandler)

httpd.socket = ssl.wrap_socket (httpd.socket,
keyfile='/path/to/key.pem',
certfile='/path/to/cert.pem', server_side=True)

httpd.serve_forever()

python 2.x

1
2
3
4
5
6
7
8
9
10
11
import BaseHTTPServer, SimpleHTTPServer
import ssl

httpd = BaseHTTPServer.HTTPServer(('localhost', 443),
SimpleHTTPServer.SimpleHTTPRequestHandler)

httpd.socket = ssl.wrap_socket (httpd.socket,
keyfile='/path/to/key.pem',
certfile='/path/to/cert.pem', server_side=True)

httpd.serve_forever()

制作私钥证书

1
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365

执行此命令后,根据交互式提示,输入必要的保护密码,以及后续的可选填信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
➜  ~ openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365
Generating a RSA private key
......+++++
...........................+++++
writing new private key to 'key.pem'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:CN
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:
Email Address []:

执行

因为https使用443端口,所以启动服务时,需要以root权限才可以绑定1024以内的端口号。之后根据提示,输入之前在制作证书阶段时的保护密码,即可提供服务。

1
2
3
➜  sudo python https.py                                               
Enter PEM pass phrase:

请求方手动安装证书

因制作的个人证书不被系统承认,所以需要手动将证书安装到系统里。

1
2
3
sudo mkdir /usr/local/share/ca-certificates/extra
sudo cp root.cert.pem /usr/local/share/ca-certificates/extra/root.cert.crt
sudo update-ca-certificates

无证书命令行请求

可以使用curl命令里的 -k 选项,跳过证书验证阶段。

1
-k, --insecure      Allow insecure server connections when using SSL

参考资料

  1. https://blog.anvileight.com/posts/simple-python-http-server/
  2. https://askubuntu.com/questions/1007233/importing-root-ca-certificate-in-linux