python快速搭建https服务器

本文介绍了使用python脚本搭建https服务器的过程

经测试验证:本文脚本在Ubuntu/Windows操作系统上均能运行

在一台连接到网络的主机上搭建https服务器,假设该主机的ip地址为:10.98.69.174

创建证书example.crt和私钥example.key

openssl req -newkey rsa:2048 -nodes -keyout example.key -x509 -days 365 -out example.crt

使用命令可以查看证书详情

openssl x509 -in example.crt -text -noout

编辑python脚本文件https_server.py

import json
import ssl
from http.server import HTTPServer, BaseHTTPRequestHandler


class MyRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # self.log_message('%s', "do_GET")
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(bytes(json.dumps({"data": "hello"}), 'utf-8'))


if __name__ == '__main__':
    context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    context.load_cert_chain(certfile='./example.crt', keyfile="./example.key")

    ciphers = ""
    ciphers += "ECDHE-ECDSA-AES128-GCM-SHA256:"
    ciphers += "ECDHE-ECDSA-CHACHA20-POLY1305:"
    ciphers += "ECDHE-RSA-CHACHA20-POLY1305:"
    ciphers += "ECDHE-RSA-AES128-GCM-SHA256:"
    context.set_ciphers(ciphers)

    ciphers_suit = context.get_ciphers()
    for i in range(len(ciphers_suit)):
        print(f"{i}: {ciphers_suit[i]['name']}")

    httpd = HTTPServer(('0.0.0.0', 4443), MyRequestHandler)
    httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
    httpd.serve_forever()

然后运行python脚本

python3 https_server.py

可以在局域网内通过火狐浏览器访问 https://10.98.69.174:4443 查看https服务器是否已经生效

本文在写作中,以下文章给作者带来了很大的帮助,特此表示感谢

快速架设Python HTTPS服务 – 又是火星人 – 博客园

作者:乐观的lishan

物联沃分享整理
物联沃-IOTWORD物联网 » python快速搭建https服务器

发表回复