python秒起https 文件服务器
代码语言:javascript复制前几天博客有个秒级启动http web服务器:
python -m http.server 6666
结果有同事想要求换成https web服务器,所以就有了下文
文章在这里:
python实现秒级启动http、ftp服务器
一、windows版本:
1.安装openssl
openssl官方下载地址
下载msi版本,一路下一步,最后一步全部取消勾选,这里有坑
配置环境变量就和python一样了
第二天我会上传到工作群,openssl安装包
2.生成证书
代码语言:javascript复制openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
3.启动https服务
代码语言:javascript复制# coding=utf-8
"""
@Project :pachong-master
@File :httpserver.py
@Author :gaojs
@Date :2022/8/17 22:29
@Blogs : https://www.gaojs.com.cn
"""
import http.server
import ssl
def https_web_server():
"""
https服务器
:return:
"""
server_ip = 'localhost'
# 这里port不要写成字符串,我刚开始给成字符串,报错搞了好一会
server_port = 5001
server_address = (server_ip, server_port)
# 生成证书步骤:
# openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
server_cert = "./cert.pem"
server_key = "./key.pem"
httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(
httpd.socket,
server_side=True,
certfile=server_cert,
keyfile=server_key,
ssl_version=ssl.PROTOCOL_TLS)
print("Server HTTPS on " server_ip " port " str(server_port) " (https://" server_ip ":" str(server_port) ") ... ")
httpd.serve_forever()
if __name__ == '__main__':
https_web_server()
4.结果如下
二、linux版本
1.生成证书
我这里使用的是阿里云的镜像,所以默认自带openssl
代码语言:javascript复制openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
2.启动https服务器
代码语言:javascript复制# coding=utf-8
"""
@Project :pachong-master
@File :httpserver.py
@Author :gaojs
@Date :2022/8/17 22:29
@Blogs : https://www.gaojs.com.cn
"""
import http.server
import ssl
def https_web_server():
"""
https服务器
:return:
"""
server_ip = 'localhost'
server_port = 5001
server_address = (server_ip, server_port)
# 生成证书步骤:
# openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
server_cert = "./cert.pem"
server_key = "./key.pem"
httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(
httpd.socket,
server_side=True,
certfile=server_cert,
keyfile=server_key,
ssl_version=ssl.PROTOCOL_TLS)
print("Server HTTPS on " server_ip " port " str(server_port) " (https://" server_ip ":" str(server_port) ") ... ")
httpd.serve_forever()
if __name__ == '__main__':
https_web_server()
三、加入腾讯云自媒体分享计划
我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=1otwwvb9ht470