使用 python 创建最简单的 https 服务器

本文介绍了一个使用Python编写的简易HTTPS服务器。该服务器通过openssl生成证书,并利用BaseHTTPServer和SimpleHTTPServer模块提供HTTPS服务。文章提供了运行服务器的具体步骤及如何在浏览器中访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此文版权属于作者所有,任何人、媒体或者网站转载、借用都必须征得作者本人同意!

#!/usr/bin/env python

# taken from https://gist.github.com/dergachev/7028596
# 
# generate server.xml with the following command:
#   openssl req -new -x509 -keyout https_svr_key.pem -out https_svr_key.pem -days 3650 -nodes
#
# run as follows:
#    python https_svr.py
#
# then in your browser, visit:
#    https://localhost:4443
#

import BaseHTTPServer
import SimpleHTTPServer
import os
import socket
import ssl

script_home = os.path.dirname(os.path.abspath(__file__))
ip = [(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) \
      for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
port = 4443

def main():
    print ("simple https server, address:%s:%d, document root:%s" % (ip, port, script_home))

    httpd = BaseHTTPServer.HTTPServer(('0.0.0.0', port), SimpleHTTPServer.SimpleHTTPRequestHandler)
    httpd.socket = ssl.wrap_socket(httpd.socket, certfile='./https_svr_key.pem', server_side=True)
    httpd.serve_forever()

if __name__ == '__main__':
    os.chdir(script_home)
    main()



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值