目 录CONTENT

文章目录

如何使用Python2启动一个https服务器?

phyger
2022-10-31 / 0 评论 / 5 点赞 / 1,936 阅读 / 874 字 / 正在检测是否收录...

1、前言

最近因为需要对正向代理的https代理功能进行测试。所以需要模拟一个简单的https服务端,在完成测试后,特将测试过程记录下来,形成此文。

2、https服务器搭建

2.1、生成自签证书

一般的机器上都会安装openssl工具,如果你的机器未安装,请首先安装openssl。

# 生成key文件(生成过程中需要输入密码,记下这个密码后面有用,假设密码为1234)
openssl genrsa -des3 -out localhost.key 1024

# 使用key文件生成证书
openssl req -new -x509 -key localhost.key -days 750 -out localhost.pem

执行完如上命令,会在当前路径下生成localhost.key和localhost.pem文件,供后面的https服务器代码使用。

2.2、编写https服务器代码

文件名:hts.py

import BaseHTTPServer
import SimpleHTTPServer
import SocketServer
import ssl

class ThreadedHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
    print "start..."
    pass

httpd = ThreadedHTTPServer(('0.0.0.0', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, keyfile="localhost.key", certfile="localhost.pem", server_side=True)
httpd.serve_forever()

2.3、启动https服务器

使用命令:python hts.py,启动过程中需要输入生成key文件时的密码1234,然后回车即可。

image-20221031151027015

然后就可以通过客户端进行访问测试了。

5

评论区