Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 699
vskbdvds Avatar asked Jan 28 '26 07:01

vskbdvds


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.

like image 131
Lie Ryan Avatar answered Jan 29 '26 21:01

Lie Ryan


Here is what you are looking for.


# WEBSERVER with SSL support
# Create certificate files ca_key.pem and ca_cert.pem and they should be in the same folder

# Output when client connects:
# Web Server at => 192.168.1.100:4443
# 192.168.1.22 - - [12/Feb/2022 02:32:56] "GET /default.html HTTP/1.1" 200 -
import http.server
import ssl

HOST = '192.168.1.100'
PORT = 4443
Handler = http.server.SimpleHTTPRequestHandler
with http.server.HTTPServer((HOST, PORT), Handler) as httpd:
    print("Web Server listening at => " + HOST + ":" + str(PORT))
    sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    sslcontext.load_cert_chain(keyfile="ca_key.pem", certfile="ca_cert.pem")
    httpd.socket = sslcontext.wrap_socket(httpd.socket, server_side=True)
    httpd.serve_forever()

like image 25
Sukesh Ashok Kumar Avatar answered Jan 29 '26 19:01

Sukesh Ashok Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!