Skip to main content
 首页 » 编程设计

python之尝试使用 LetsEncrypt 在 Python 中运行 SSL-wrapped BaseHTTPServer 失败

2024年10月17日26lvdongjie

我有一个使用 Python 中的 BaseHTTPServer 的工作 HTTP 服务器,所以我尝试添加一个 SSL 证书以允许使用 LetsEncrypt 的 https,现在它不会提供任何文件或响应。不会抛出异常或错误,也不会提供任何内容。

server_address = ('0.0.0.0', 80) 
httpd = HTTPServer(server_address, MyHandler) 
# I can comment out the following line and it'll work 
httpd.socket = ssl.wrap_socket(httpd.socket, keyfile=ssl_key, certfile=ssl_cert, server_side=True) 
httpd.serve_forever() 
 
#ssl_key = '/etc/letsencrypt/live/example.com/privkey.pem' 
#ssl_cert = '/etc/letsencrypt/live/example.com/fullchain.pem' 

其中 MyHandler 如下:

class MyHandler(BaseHTTPRequestHandler): 
    def do_GET(self): 
        self.send_response(204) 
        self.send_header("Content-Type", "text/html") 
        self.end_headers() 
        return 
 
    def do_POST(self): 
        self.send_response(204) 
        self.send_header("Content-Type", "text/html") 
        self.end_headers() 
        return 

尝试通过 Web 浏览器从 https://example.com 访问站点时返回标准无响应“未找到服务器”。

我按照以下说明使用 LetsEncrypt 生成证书:https://certbot.eff.org/#ubuntuxenial-other

sudo apt-get install letsencrypt

接着是:

letsencrypt certonly --standalone -d example.com

有什么方法可以让我轻松找出这里的问题所在?使用 Python 3.5。如果需要,很乐意提供更多信息。

请您参考如下方法:

server_address = ('0.0.0.0', 80) 

Attempting to access the site via web browser from https://example.com returns a standard no-response "Server not found".

https://host 没有明确的端口指定意味着服务器在 https 协议(protocol)的默认端口上访问,即 443。但是,您已将服务器设置为使用端口 80 服务器地址。

有两种方法可以解决此问题:在 URL 中为 https 显式指定一个非标准端口,即 https://host:80 或更改 server_address< 中的端口 从 80 到 443。最后一个选项可能更好。