Skip to content

Instantly share code, notes, and snippets.

@SeanPesce
Last active May 6, 2024 18:01
Show Gist options
  • Save SeanPesce/af5f6b7665305b4c45941634ff725b7a to your computer and use it in GitHub Desktop.
Save SeanPesce/af5f6b7665305b4c45941634ff725b7a to your computer and use it in GitHub Desktop.
Simple Python 3 HTTPS Server (SSL/TLS)
#!/usr/bin/env python3
# Author: Sean Pesce
# References:
# https://stackoverflow.com/questions/19705785/python-3-simple-https-server
# https://docs.python.org/3/library/ssl.html
# https://docs.python.org/3/library/http.server.html
# Shell command to create a self-signed TLS certificate and private key:
# openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out cert.crt -keyout private.key
import http.server
import ssl
import sys
def serve(host, port, cert_fpath, privkey_fpath):
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.load_cert_chain(certfile=cert_fpath, keyfile=privkey_fpath, password='')
server_address = (host, port)
httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
httpd.serve_forever()
if __name__ == '__main__':
if len(sys.argv) < 4:
print(f'Usage:\n {sys.argv[0]} <port> <PEM certificate file> <private key file>')
sys.exit()
PORT = int(sys.argv[1])
CERT_FPATH = sys.argv[2]
PRIVKEY_FPATH = sys.argv[3]
serve('0.0.0.0', PORT, CERT_FPATH, PRIVKEY_FPATH)
@SeanPesce
Copy link
Author

SeanPesce commented Mar 3, 2023

This Python 3 script mimics the behavior of python2.7 -m SimpleHTTPServer 80 and python3 -m http.server 80, but with support for SSL/TLS/HTTPS.

Usage:

python3 ./https_server.py <port> <PEM certificate file> <private key file>

Example:

python3 ./https_server.py 443 ./cert.crt ./private.key

Example command to create a self-signed TLS certificate and private key:

openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out cert.crt -keyout private.key

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment