HTTPS with Python 2.7 CGIHTTPServer



我已经有一个使用 Python 2.7 CGIHTTPServer 运行的 Web 服务。 太好了。它很轻巧。但是,我现在要求它与HTTPS和我拥有的证书一起使用。关于如何执行此操作的说明很少。事实上,我只找到了一篇关于 Python 2.7 的文章。

我的问题很简单,而且非常狭窄。鉴于以下说明,如何启动它?我已经有一个基于事务的python脚本。 你调用它,它处理你的请求。它需要SSL。

https://blog.farville.com/15-line-python-https-cgi-server

这需要一个目录结构:

/ssl_server.py
/localhost.pem
/html/index.html   html lives here, aka “root directory”
/html/cgi/         python scripts live here

使用 openssl 制作的自签名 SSL 证书,如下所示:

openssl req -x509 -sha256 -newkey rsa:2048 -keyout localhost.pem 
-out localhost.pem -days 3650 -nodes

ssl_server.py:

#!/usr/bin/env python
import os, sys
import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable() ## This line enables CGI error reporting
import ssl
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8443)
handler.cgi_directories = ["/cgi"]
os.chdir("html")
srvobj = server(server_address, handler)
srvobj.socket = ssl.wrap_socket (srvobj.socket, certfile="../localhost.pem", server_side=True)
# Force the use of a subprocess, rather than
# normal fork behavior since that doesn't work with ssl
handler.have_fork=False
srvobj.serve_forever()

那现在怎么办?同样,请记住,我有另一个已经成功处理 Web 请求的 python 脚本。

我在证书文件旁边添加了密钥文件,并执行了python ssl_server.py,它有效

srvobj.socket = ssl.wrap_socket (srvobj.socket, certfile="/etc/letsencrypt/live/myowndomain.com/cert.pem", keyfile="/etc/letsencrypt/live/myowndomain.com/privkey.pem" server_side=True)

最新更新