HTTPS与Python 2.7 CGIHTTPServer

时间:2017-05-22 05:03:29

标签: python ssl cgi-bin

我已经有一个使用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脚本。

1 个答案:

答案 0 :(得分:1)

我在证书文件旁边添加了密钥文件,并执行了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)