Posted by & filed under Programming & Sysadmin, Web development.

For python 2.7

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

 

 Here’s a multithreaded version:

ssl_server.py:

#!/usr/bin/env python
import os, sys
import BaseHTTPServer
import CGIHTTPServer
import SocketServer
import cgitb; cgitb.enable() ## This line enables CGI error reporting
import ssl

class ThreadingCGIServer(SocketServer.ThreadingMixIn,BaseHTTPServer.HTTPServer):
     pass

handler = CGIHTTPServer.CGIHTTPRequestHandler
handler.cgi_directories = ["/scripts"]
os.chdir("html")
server = ThreadingCGIServer(("", 8443), handler)
server.socket = ssl.wrap_socket (server.socket, certfile="../localhost.pem", server_side=True)handler.have_fork=False
try:
     while 1:
          sys.stdout.flush()
          server.handle_request()
except KeyboardInterrupt:
     print "Finished"

 

Trackbacks/Pingbacks

  1.  HTTPS with Python 2.7 CGIHTTPServer Rapid Python

Leave a Reply

  • (will not be published)