网站Logo 知识武装灵魂

证书申请脚本-腾讯云API

admin
7
2025-08-18

使用腾讯云API申请免费证书,同时直接部署到nginx配置下。

import json,base64,os,types
import zipfile
import shutil
from pathlib import Path
from time import time,sleep
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ssl.v20191205 import ssl_client, models

start = time()
# 请使用环境变量获取。不要硬编码
cred = credential.ProfileCredential().get_credential()
httpProfile = HttpProfile()
httpProfile.endpoint = "ssl.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
domain_name = []
while True:
 domain = input('要申请证书的域名:')输入一个域名,然后回车两次。
 if domain == '':
     break
 else:
     domain_name.append(domain)

for i in range(len(domain_name)):
 client = ssl_client.SslClient(cred, "", clientProfile)
 try:
     req = models.ApplyCertificateRequest()
     params = {
         "DvAuthMethod": "DNS_AUTO",
         "DomainName": domain_name[i]
     }
     req.from_json_string(json.dumps(params))
     resp = client.ApplyCertificate(req)
     print(resp.to_json_string())
     response = json.loads(resp.to_json_string())
     print('域名:{0}资料已提交,五秒钟后自动验证'.format(domain_name[i]))
     certid = response['CertificateId']
     print(certid)
     sleep(30)
     try:
         req1 = models.CompleteCertificateRequest()
         params1 = {
             "CertificateId": certid
         }
         req1.from_json_string(json.dumps(params1))

         resp1 = client.CompleteCertificate(req1)
         response1 = json.loads(resp1.to_json_string())
         print('域名:{0}正在验证'.format(domain_name[i]))
         sleep(30)
         print("验证完成,正在下载")
         try:
             req2 = models.DownloadCertificateRequest()
             params2 = {
                    "CertificateId": certid
             }
             req2.from_json_string(json.dumps(params2))

             # 返回的resp是一个DownloadCertificateResponse的实例,与请求对象对应
             resp2 = client.DownloadCertificate(req2)
             # 输出json格式的字符串回包
             print(resp2.to_json_string())
             response2 = json.loads(resp2.to_json_string())
             content = response2['Content']
             os.makedirs("/data/cert", exist_ok=True)
             zip_path = os.path.join("/data/cert", f"{domain_name[i]}.zip")
             with open(zip_path, "wb") as f:
                 f.write(base64.b64decode(content))
         except TencentCloudSDKException as err:
             print(err)
     except TencentCloudSDKException as err:
         print(err)
 except TencentCloudSDKException as err:
     print(err)

zip_path = f"/data/cert/{domain}.zip"  # 下载的ZIP路径
extract_dir = f"/data/cert/{domain}"  # 解压目录
nginx_cert_dir = "/etc/nginx/cert"  # Nginx证书存储目录

# 2. 确保目录存在
os.makedirs(extract_dir, exist_ok=True)
os.makedirs(nginx_cert_dir, exist_ok=True)

try:
    # 3. 解压ZIP文件
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(extract_dir)
    print(f"[OK] 解压完成: {zip_path} -> {extract_dir}")

    # 4. 定位Nginx证书文件 (通常为 1_域名_bundle.crt 和 2_域名.key)
    nginx_crt = list(Path(f"{extract_dir}/Nginx").glob("1_*_bundle.crt"))
    nginx_key = list(Path(f"{extract_dir}/Nginx").glob("2_*.key"))

    if not nginx_crt or not nginx_key:
        raise FileNotFoundError("找不到Nginx证书文件")

    # 5. 复制到Nginx目录 (并重命名为标准格式)
    shutil.copy(str(nginx_crt[0]), f"{nginx_cert_dir}/{domain}_bundle.crt")
    shutil.copy(str(nginx_key[0]), f"{nginx_cert_dir}/{domain}.key")
    print(f"[OK] 证书已复制到: {nginx_cert_dir}")

    # 6. 设置权限 (Nginx需要读取权限)
    os.chmod(f"{nginx_cert_dir}/{domain}.crt", 0o644)
    os.chmod(f"{nginx_cert_dir}/{domain}.key", 0o600)
    print("[OK] 文件权限已设置")

except Exception as e:
    print(f"[ERROR] 处理失败: {e}")
finally:
    # 7. 清理临时解压文件 (可选)
    shutil.rmtree(extract_dir, ignore_errors=True)
end = time()
print('本次代码执行共耗时:', round(end - start, 2), 's')