#!/usr/bin/python
# -*- coding:utf-8 -*-
#
# !请先使用 pip install aliyun-python-sdk-cdn 安装 sdk!
 
from aliyunsdkcore import client
from aliyunsdkcdn.request.v20141111 import SetDomainServerCertificateRequest
import datetime
import os
import collections
import hashlib
import json
 
ABS_PATH = os.path.abspath('.')
JSON_PATH = os.path.join(ABS_PATH, 'data.json')
## 配置开始
# 访问 https://ak-console.aliyun.com/index#/accesskey 获取
AccessKeyId = ''
AccessKeySecret = ''
 
# 指定证书所属加速域名,需属于https加速类型
# !!! 修改域名元组后请将 data.json 删除
DomainName = ['jackyu.cn', 'beta.uozi.org']
Letsencrypt_path = os.path.join('/etc/letsencrypt')
live_cert = os.path.join(Letsencrypt_path, 'live')
## 配置结束
 
# 获取证书 md5 返回: 字典
def key_md5():
    domain = collections.OrderedDict()
    for d in DomainName:
        privkey = os.path.join(live_cert, d, 'privkey.pem')
        md5 = hashlib.md5(privkey).hexdigest()
        domain[d] = md5
 
    return domain
 
# 写入数据
def write_data(domain):
    with open(JSON_PATH, 'w') as json_file:
        json_file.write(json.dumps(domain))
 
# 获取数据
def load_data():
    with open(JSON_PATH) as json_file:
        data = json.load(json_file)
        return data
# 判断数据文件是否存在
if not os.path.exists(JSON_PATH):
    # 将私钥的 md5 写入 Json
    write_data(key_md5())
 
 
domain = key_md5()
data = load_data()
 
for d in DomainName:
    if not data[d] == domain[d]:
        try:
            Client = client.AcsClient(AccessKeyId, AccessKeySecret, 'cn-hangzhou')
            request = SetDomainServerCertificateRequest.SetDomainServerCertificateRequest()
            request.set_accept_format('json')
            CertName = d + '_' + datetime.datetime.now().strftime("%Y%m%d_%H%M%S") # 证书名称,默认域名+日期时间
            ServerCertificate_path = os.path.join(live_cert, d, 'fullchain.pem') # 安全证书路径
            PrivateKey_path = os.path.join(live_cert, d, 'privkey.pem') # 私钥路径
 
            request.set_DomainName(d)
            request.set_CertName(CertName)
            request.set_ServerCertificateStatus('on')
            ServerCertificate = open(ServerCertificate_path, 'r').read()
            ServerCertificate = open(ServerCertificate_path, 'r').read()
            PrivateKey = open(PrivateKey_path, 'r').read()
            request.set_ServerCertificate(ServerCertificate)
            request.set_PrivateKey(PrivateKey)
            result = Client.do_action_with_exception(request)
            print(result)
        except ServerException as e:
            print('Domain:'+d+'Error:'+e)
 
        # 更新数据文件
        os.remove(JSON_PATH)
        write_data(key_md5())
最后修改:2020 年 02 月 13 日 11 : 31 PM
如果觉得我的文章对你有用,请随意赞赏