Python -m http.server 443 -- with SSL?

Viewed 11768

Is it possible to create a temporary Python3 HTTP server with an SSL certificate? For example:

$ python3 -m http.server 443 --certificate /path/to/cert
2 Answers

Not from the command line, but it's pretty straightforward to write a simple script to do so.

from http.server import HTTPServer, BaseHTTPRequestHandler 
import ssl
httpd = HTTPServer(('localhost', 4443), BaseHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(
    httpd.socket,
    keyfile="path/to/key.pem",
    certfile='path/to/cert.pem',
    server_side=True)
httpd.serve_forever()

Credit

If you are not restricted to the standard library and can install pip packages, there are also a number of other options, for example you can install uwsgi, which accepts command line options.

Actually no, but there is an implementation that uses the same package with ssl. You should try it.

The script is written using Python 2 but it is pretty easy to implement again with Python 3 since it is 5 lines.

The http.server is the Python 3 is the equivalent to SimpleHTTPServer from Python 2.

import BaseHTTPServer, SimpleHTTPServer
import ssl

httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./server.pem', server_side=True)
httpd.serve_forever()

Script credits to dergachev

Related