Let's Encrypt + Tornado 开启HTTPS

  1. Let’s Encrypt安装
git clone https://github.com/letsencrypt/letsencrypt
cd letsencrypt
./letsencrypt-auto --help

*文件夹位置无要求。第三步安装python依赖时可能出问题,当出现Installed succeeded时即完成安装,可以生成证书了。

2.Let’s Encrypt 生成证书

(1)自动生成

./letsencrypt-auto certonly --standalone --email your@email.com -d your.website.com

(2)手动生成(自动生成一直报各种error,因此选择了手动)

letsencrypt certonly --email your@email.com -d your.website.com -a manual

在出现Press ENTER to continue时不要按回车,按照提示验证http服务器(80端口)。

假设提示如下,则tornado按照下方设置:

Make sure your web server displays the following content at
http://your.website.com/.well-known/acme-challenge/TpEfZ8OlplOnPccqRflFQJx4RlyLBrFWSSOmyyMz_hg 
before continuing:
TpEfZ8OlplOnPccqRflFQJx4RlyLBrFWSSOmyyMz_hg.AFXCrRqWY4MoK3ELD3znRadP4xAVV4zSDb9Mj0JTHDg
class TestHandler(tornado.web.RequestHandler):
  def get(self): 
    self.write('TpEfZ8OlplOnPccqRflFQJx4RlyLBrFWSSOmyyMz_hg.AFXCrRqWY4MoK3ELD3znRadP4xAVV4zSDb9Mj0JTHDg')
  def post(self):
    self.get()

def make_app():
  return tornado.web.Application([(r"/.well-known/acme-challenge/TpEfZ8OlplOnPccqRflFQJx4RlyLBrFWSSOmyyMz_hg", TestHandler)], debug=True, static_path=os.path.dirname(__file__))

完成后将会在/etc/letsencrypt/live/下生成四个文件privkey.pem, fullchain.pem, cert.pem, chian.pem。tornado只需要用到privkey.pem, fullchain.pem。

  1. Tornado搭建HTTPS服务器
import os.path

from tornado import httpserver
from tornado import ioloop
from tornado import web

class TestHandler(web.RequestHandler):
    def get(self):
        self.write("Hello, World!")

def main():
    settings = {
        "static_path": os.path.join(os.path.dirname(__file__), "static"),
    }
    application = web.Application([
        (r"/", TestHandler),
    ], **settings)
    server = httpserver.HTTPServer(application, ssl_options={
           "certfile": os.path.join(os.path.abspath("."), "fullchain.pem"),
           "keyfile": os.path.join(os.path.abspath("."), "privkey.pem"),
    })
    server.listen(8000)
    ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

你可能感兴趣的:(python)