步骤一:生成签名证书
安装openssl
sudo apt-get install openssl
sudo apt-get install libssl-dev
创建私钥:
openssl genrsa -out ca-key.pem 1024
创建csr证书请求
openssl req -new -key ca-key.pem -out ca-req.csr -subj "/C=CN/ST=BJ/L=BJ/O=BJ/OU=BJ/CN=BJ"
生成crt证书:
openssl x509 -req -in ca-req.csr -out ca-cert.pem -signkey ca-key.pem -days 3650
创建服务端私钥:
openssl genrsa -out server-key.pem 1024
创建csr证书:
openssl req -new -out server-req.csr -key server-key.pem -subj "/C=CN/ST=BJ/L=BJ/O=BJ/OU=BJ/CN=BJ"
生成crt证书
openssl x509 -req -in server-req.csr -out server-cert.pem -signkey server-key.pem -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -days 3650
确认证书:
openssl verify -CAfile ca-cert.pem server-cert.pem
步骤二:启动HTTPS服务
通过python(3.6)模块,启动HTTPS服务。可以在后台运行python程序,并返回结果。可以通过访问`https://ip/a.py?argv`运行
实例代码:
#-*-coding:utf-8-*-
from http import server
from http.server import BaseHTTPRequestHandler
import socket
import ssl
import sys
import subprocess
import os
#自义定一个处理模块
class RequestHandler(BaseHTTPRequestHandler):
def send_content(self, page, status =200):
self.send_response(status)
self.send_header("Content-type","text/html")
self.send_header("Content-Length",str(len(page)))
self.end_headers()
if type(page) == type('a'):
self.wfile.write(bytes(page,encoding = 'utf-8'))
elif type(page) == type(b'1'):
self.wfile.write(page)
print("response: ",page)
#执行python程序,这里也可以自己修改,执行任意代码
def runpy(self, path, query):
try:
res =subprocess.check_output("python %s %s"%(path, query),
stderr= subprocess.STDOUT,
shell= True)
self.send_content(res)
except subprocess.CalledProcessError as exc:
res = "returncode:%r<br/>" % exc.returncode
res += "cmd: %s<br/>"% exc.cmd
res += "output:%s<br/>" % exc.output
self.send_content(res)
#处理GET请求
def do_GET(self):
print("self.path",self.path)
if "?" in self.path:
path, query =self.path.split('?')
self.full_path =os.getcwd() + path
if(os.path.isfile(self.full_path) and self.full_path.endswith('.py')):
print("runing%s"%path.lstrip('/'))
self.runpy(path.lstrip('/'),query)
else:
print("%s not exist"%path)
self.send_content("%s not exist"%path)
else:
self.send_content("Hello, World")
#监听端口
port =443
try:
httpd =server.HTTPServer(("0.0.0.0", port),RequestHandler)
except:
port = 8443
httpd =server.HTTPServer(("0.0.0.0", port),RequestHandler)
context= ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain("server-cert.pem","server-key.pem")
httpd.socket= context.wrap_socket(httpd.socket, server_side = True)
try:
print("HTTTPS Server listening on0.0.0.0:%d"%port)
httpd.serve_forever()
exceptKeyboardInterrupt:
print("User quit.")
exit()