Python Webserver
|Example of Regular HTTP Static Web Server
Python 3.x
1 | python3 -m http.server 8000 --bind 127.0.0.1 |
Both port and bind address are optional. For more details, please read the official docs.
Python 2.x
1 | python -m SimpleHTTPServer 8000 |
Python 2.x can only accept port as a parameter Bind address parameter is not available.Python 2.x Docs.
In both cases contents of the current folder will be accessible via http://127.0.0.1:8000
1 2 3 4 5 6 7 8 9 | from http.server import HTTPServer, BaseHTTPRequestHandler import ssl httpd = HTTPServer(('localhost', 4443), SimpleHTTPRequestHandler) httpd.socket = ssl.wrap_socket (httpd.socket, keyfile='path/to/key.pem', certfile='path/to/cert.pem', server_side=True) httpd.serve_forever() |
Example with SSL Support
To run secure HTTPs server create a following module:
Python 3.x
1 2 3 4 5 6 7 8 9 10 11 | from http.server import HTTPServer, BaseHTTPRequestHandler import ssl httpd = HTTPServer(('localhost', 4443), SimpleHTTPRequestHandler) httpd.socket = ssl.wrap_socket (httpd.socket, keyfile="path/to/key.pem", certfile='path/to/cert.pem', server_side=True) httpd.serve_forever() |
Python 2.x
1 2 3 4 5 6 7 8 9 10 11 12 | import BaseHTTPServer, SimpleHTTPServer import ssl httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler) httpd.socket = ssl.wrap_socket (httpd.socket, keyfile="path/tp/key.pem", certfile='path/to/cert.pem', server_side=True) httpd.serve_forever() |
To generate key and cert files with OpenSSL use following command
1 | openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 |