python实现简单的https服务器

By | 2022年4月26日

以下提供一个简单的方式快速部署一个https服务器,用于非生产环境的测试使用,如果是正式的生产环境,考虑到性能安全等因素,就不要使用这个了。

1、使用pyOpenSSL库:

# coding:utf-8
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
from SocketServer import BaseServer
from OpenSSL import SSL
import socket, os

def main():
    print "Start web server ..."
    webServerPort = 31000
    httpserver = ThreadedHTTPServer(("", webServerPort), WelcomeHandler)
    try:
        httpserver.serve_forever()
    except(KeyboardInterrupt):
        print "\nStop web server ..."
    
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    def __init__(self, server_address, HandlerClass):
        BaseServer.__init__(self, server_address, HandlerClass)
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey_file("nfvo_https.key")
        ctx.use_certificate_file("nfvo_https.pem")
        self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
        self.socket.setblocking(0)
        self.server_bind()
        self.server_activate()

    def finish_request(self,request, client_address):
        try:
            self.RequestHandlerClass(request, client_address, self)
        except SSL.ZeroReturnError:
            self.close_request(request)

    def shutdown_request(self,request):
        request.shutdown()

class WelcomeHandler(BaseHTTPRequestHandler):
    def setup(self):
        self.connection = self.request
        self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
        self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)

    def response(self, code, htmlPage):
        self.send_response(code)
        self.send_header("Content-type","text/html")
        self.end_headers()
        self.wfile.write(htmlPage)

    def do_GET(self):
        if self.path  == "/hello":
            self.response(200,"Hello World.\n")
            return
        self.response(200,"GET request.\n")

    def do_POST(self):
        self.response(200,"POST request.\n")

    def do_PUT(self):
        self.response(200,"PUT request.\n")

if __name__ == '__main__':
    main()

2、使用自带ssl库(python 2.6之后):

# coding:utf-8

import BaseHTTPServer, SimpleHTTPServer
from SocketServer import ThreadingMixIn
import ssl
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

def main():
    httpd = ThreadedHTTPSServer(('0.0.0.0', 31001), WelcomeHandler)
    httpd.socket = ssl.wrap_socket(httpd.socket, \
                                certfile='nfvo_https.pem', \
                                keyfile="nfvo_https.key", \
                                server_side=True)
    try:
        httpd.serve_forever()
    except(KeyboardInterrupt):
        print "\nStop web server ..."

class ThreadedHTTPSServer(ThreadingMixIn, HTTPServer):
    """ this is a example https server"""

class WelcomeHandler(BaseHTTPRequestHandler):

    def response(self, code, htmlPage):
        self.send_response(code)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(htmlPage)

    def do_GET(self):
        if self.path == "/hello":
            self.response(200, "Hello World.\n")
            return
        self.response(200, "GET request.\n")

    def do_POST(self):
        self.response(200, "POST request.\n")

    def do_PUT(self):
        self.response(200, "PUT request.\n")

if __name__ == '__main__':
    main()
Category: 未分类 标签:

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注