For a test suite I need to create a local SSL-enabled HTTPS server in my Python project. I googled around and found various recipes using pyOpenSSL, but all of those are quite complicated, and I didn’t even get the referenced one to work.
Also, Python has shipped its own built-in SSL module for quite a while. After reading some docs and playing around, I eventually got it to work with a remarkably simple piece of code using the builtin ssl module:
import BaseHTTPServer, SimpleHTTPServer
import ssl
httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile='path/to/localhost.pem', server_side=True)
httpd.serve_forever()
(I use port 4443 so that I can run the tests as normal user; the usual port 443 requires root privileges).
Way to go, Python!
#1 by Jeppe on 2011/01/18 - 19:59
Zitieren
Thank you very much for sharing this. I have been looking for a simple solution for a while now, so this fits perfectly.
#2 by Shuen on 2012/02/20 - 15:04
Zitieren
Does that mean the server does not do a handshake?
Do I need to add httd.socket.do_handshake()?
#3 by Gregg Lind on 2012/03/14 - 21:58
Zitieren
Would you mind sharing your process for generating the PEM file?
#4 by pitti on 2012/03/15 - 08:38
Zitieren
It’s done with the “openssl x509″ command. See “man x509″ and /usr/share/doc/openssl/HOWTO/certificates.txt.gz .
#5 by Eric Rosenbloom on 2012/10/10 - 21:32
Zitieren
This made my day! Thanks
#6 by Marcus on 2012/10/20 - 19:44
Zitieren
Did you figure out how to make it work with a third party commercial ssl issuer? I let js talk to a py script and the webkit lot of browsers gets very upset over self signed certs.
#7 by pitti on 2012/10/22 - 07:00
Zitieren
This isn’t really related to the creation of the SSL certificate. ‘path/to/localhost.pem’ can be a locally created self-signed cert or a “real” one from an actual provider.
#8 by Joscha on 2013/01/11 - 02:00
Zitieren
This should do:
openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes
Pingback: How to send and receive files like a professional | The Technical Blog of James
#9 by Rafael Rinaldi on 2013/03/10 - 04:39
Zitieren
It runs for me but nothing is being served on localhost.