简体   繁体   中英

HTTPS with Python 2.7 CGIHTTPServer

I already have a web service running using Python 2.7 CGIHTTPServer. It's great. It's lightweight. However, I now require it to work with HTTPS and a certificate that I have. There are very few instructions on how to do this. In fact there is only one article that I found for Python 2.7.

My question is simple and very narrow. Given the instructions below, how do I launch it? I already have a python script that is transaction based. You call it, it processes your request. It needs SSL.

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

This expects a directory structure:

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

Self Signed SSL cert made with openssl like this:

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

So what now? Again, keep in mind I have another python script that already successfully processes web requests.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM