Python 3 HTTPS Webserver

MAN*_*100 23 python https

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

python -m http.server
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*kis 26

首先,您需要一个证书 - 假设我们将localhost.pem其包含包含私钥和公钥的文件中,然后:

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_TLSv1)
httpd.serve_forever()
Run Code Online (Sandbox Code Playgroud)

确保为其指定正确的参数wrap_socket!

  • 如上所述,如果证书不包含私钥,则需要指定`keyfile` - 文档是[here](https://docs.python.org/3/library/ssl.html#combined-key-和证书). (7认同)
  • 可以使用“openssl req -new -x509 -keyout localhost.pem -out localhost.pem -days 365 -nodes”生成证书(默认答案适用于快速测试)。 (7认同)
  • 我还需要指定`keyfile ='...'`。另外,例如在使用curl进行查询时,它会显示“ curl:(56)GnuTLS接收错误(-110):TLS连接未正确终止”(可以忽略,但是看起来有些丑陋) (3认同)