Python 3简单 HTTPS 服务器

我知道您可以使用 Python 3创建一个简单的 HTTP web 服务器

python -m http.server

然而,是否有一种简单的方法来保护到 WebServer 的连接,我是否需要生成证书?我要怎么做?

87079 次浏览

First, you will need a certificate - assume we have it in a file localhost.pem which contains both the private and public keys, then:

import http.server, ssl


server_address = ('localhost', 4443)
httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket,
server_side=True,
certfile='localhost.pem',
ssl_version=ssl.PROTOCOL_TLS)
httpd.serve_forever()

Make sure you specify the right parameters for wrap_socket!

Note: If you are using this to serve web traffic, you will need to use '0.0.0.0' in place of 'localhost' to bind to all interfaces, change the port to 443 (the standard port for HTTPS), and run with superuser privileges in order to have the permission to bind to a well-known port.