Python 3简单的HTTPS服务器 [英] Python 3 Simple HTTPS server

查看:1229
本文介绍了Python 3简单的HTTPS服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know you can create a simple HTTP web server in Python 3 using

python -m http.server

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

However is there a simple way to secure the connection to the WebServer, do i need to generate certificates? How would I do this?

推荐答案

首先,您将需要一个证书-假设我们在文件localhost.pem中拥有该证书,该文件同时包含私钥和公用密钥 ,然后:

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()

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

Make sure you specify the right parameters for wrap_socket!

注意:如果要使用它来提供网络流量,则需要使用'0.0.0.0'代替'localhost'绑定到所有接口,将端口更改为443(标准端口). HTTPS端口),并以超级用户权限运行,以便具有绑定到知名端口的权限.

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.

这篇关于Python 3简单的HTTPS服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆