1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| import http.server import ssl import sys
CERT_FILE = 'server.crt' KEY_FILE = 'server.key' PORT = 8443 BIND_IP = '0.0.0.0'
if len(sys.argv) > 1: PORT = int(sys.argv[1])
import subprocess import os
if not os.path.exists(CERT_FILE) or not os.path.exists(KEY_FILE): print("生成自签名证书...") ip_address = input("请输入服务器IP地址(默认 127.0.0.1): ") or "127.0.0.1"
subprocess.run([ 'openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-keyout', KEY_FILE, '-out', CERT_FILE, '-days', '365', '-nodes', '-subj', f'/CN={ip_address}', '-addext', f'subjectAltName=IP:{ip_address}' ], check=False)
handler = http.server.SimpleHTTPRequestHandler httpd = http.server.HTTPServer((BIND_IP, PORT), handler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
context.set_ciphers('DEFAULT@SECLEVEL=1:!DHE:!ECDHE')
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
print(f"HTTPS服务器已启动") print(f"访问地址: https://127.0.0.1:{PORT}") print(f"或: https://<你的IP>:{PORT}") print(f"使用证书: {CERT_FILE}") print("注意: 这是自签名证书,浏览器会显示警告") print("按 Ctrl+C 停止服务器")
try: httpd.serve_forever() except KeyboardInterrupt: print("\n服务器已停止")
|