Python HTTP/HTTPS 服务器¶
在日常运维工作中,经常需要启动一个简单的HTTP/HTTPS服务
HTTP服务¶
Python 3.x¶
在 Python 3中启动HTTP服务使用
http
模块:
python3 -m http.server 8000 --bind 127.0.0.1
Python 2.x¶
早期的 Python 2使用
SimpleHTTPServer
模块:
python -m SimpleHTTPServer 8000
HTTPS服务¶
Python 3.x (早期版本)¶
在Python 3早期版本可以使用以下代码片段来实现一个HTTPS服务:
from http.server import HTTPServer, BaseHTTPRequestHandler
import ssl
httpd = HTTPServer(('localhost', 4443), BaseHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket,
keyfile="/Users/huataihuang/bin/key.pem",
certfile='/Users/huataihuang/bin/cert.pem', server_side=True)
httpd.serve_forever()
生成服务器密钥和证书:
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365
警告
这段代码在现在的 Python 3.11 已经报错
Python 3.x¶
改为
SSLContext.wrap_socket
的Python 3.x代码片段:
import http.server, ssl, socketserver
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain("/Users/huataihuang/bin/cert.pem") # PUT YOUR cert.pem HERE
server_address = ("192.168.7.152", 4443) # CHANGE THIS IP & PORT
handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(server_address, handler) as httpd:
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
httpd.serve_forever()
警告
这段代码还有bug,待修正
生成合并cert.pm:
openssl req -new -x509 -keyout cert.pem -out cert.pem -days 365 -nodes
Pythone 2.x(待验证)¶
Python 2.x实现HTTPS代码片段:
import BaseHTTPServer, SimpleHTTPServer
import ssl
httpd = BaseHTTPServer.HTTPServer(('localhost', 4443),
SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket,
keyfile="/Users/huataihuang/bin/key.pem",
certfile='/Users/huataihuang/bin/cert.pem', server_side=True)
httpd.serve_forever()
生成服务器密钥和证书:
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365