使用Python2启动一个https服务器

1、前言

起了一个http协议的服务用来访问数据(python命令行快速搭建一个http服务),但是测试系统是https协议,跨域无法访问,所以需要启动https服务。
百度后,搬运最好使的方法:(原文章:如何使用Python2启动一个https服务器?

2、https服务器搭建

2.1、生成自签证书

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

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

# 使用key文件生成证书
openssl req -new -x509 -key localhost.key -days 750 -out localhost.pem
# 输入密码:1234
# 输入组织代码,要求不超2位数:86
# 还会让输入很多,直接回车默认

执行完如上命令,会在当前路径下(要对外开放访问的目录位置)生成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

2.3、访问

浏览器输入url即可访问https://ip地址:4443,可看到服务器启动https服务位置的文件目录,可访问文件。
image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值