banner
棒无

棒无

坟墓里寂静无比,埋葬你的是所有你未说出的话
telegram
github
bilibili
medium
email
pixiv
jike

CDN Certificate Automatic Refresh

Cause: Because configuring domestic CDNs usually requires manually uploading certificates, but the domain name certificates I applied for are usually valid for three months, so I wanted to write a script to automatically update the certificates.
Environment:
1panel (a domestic panel, automatically applies for certificates, and has other powerful functions, very convenient)

Taking the Doyun cloud I use as an example, you can find the corresponding SDK for other manufacturers.
The code is as follows:

from hashlib import sha1
import hmac
import requests
import json
import urllib

def dogecloud_api(api_path, data={}, json_mode=False):
    """
    Call the Doyun cloud API

    :param api_path:    The API interface address to call, including the URL request parameters QueryString, for example: /console/vfetch/add.json?url=xxx&a=1&b=2
    :param data:        The data to be POSTed, a dictionary, for example {'a': 1, 'b': 2}, passing this parameter indicates that it is not a GET request but a POST request
    :param json_mode:   Whether the data is requested in JSON format, the default is false, which means to use the form format (a=1&b=2)

    :type api_path: string
    :type data: dict
    :type json_mode bool

    :return dict: The returned data
    """

    # Replace with your Doyun cloud permanent AccessKey and SecretKey, which can be viewed in the user center - key management
    # Do not expose the AccessKey and SecretKey on the client, otherwise malicious users will gain full control of the account
    access_key = ''
    secret_key = ''

    body = ''
    mime = ''
    if json_mode:
        body = json.dumps(data)
        mime = 'application/json'
    else:
        body = urllib.parse.urlencode(data) # In Python 2, you can directly use urllib.urlencode
        mime = 'application/x-www-form-urlencoded'
    sign_str = api_path + "\n" + body
    signed_data = hmac.new(secret_key.encode('utf-8'), sign_str.encode('utf-8'), sha1)
    sign = signed_data.digest().hex()
    authorization = 'TOKEN ' + access_key + ':' + sign
    response = requests.post('https://api.dogecloud.com' + api_path, data=body, headers = {
        'Authorization': authorization,
        'Content-Type': mime
    })
    return response.json()
api = dogecloud_api('/cdn/cert/list.json')
if api['code'] == 200:
    for cert in api['data']['certs']:
        ssl_next_id = cert['id']
        delet_api = dogecloud_api('/cdn/cert/delete.json', {
    'id': cert['id']
})
else:
    print("api failed: " + api['msg']) # Failed
# The following two paths are the certificate paths automatically generated by 1panel
with open('/opt/1panel/apps/openresty/openresty/www/sites/xxxx/ssl/fullchain.pem') as fullchain:
    full = fullchain.read()
with open('/opt/1panel/apps/openresty/openresty/www/sites/xxxx/ssl/privkey.pem') as privkey:
    priv = privkey.read()
api = dogecloud_api('/cdn/cert/upload.json', {
    "note": f"Automatic certificate {ssl_next_id}",
    "cert": full,
    "private": priv
})
if api['code'] == 200:
    ssl_id = api['data']['id']
else:
    print("api failed: " + api['msg']) # Failed
api = dogecloud_api('/cdn/domain/config.json?domain=cdn.example.com', {
    'cert_id': ssl_id
}, True)

The basic implementation idea is to first delete the existing certificate, then add the read certificate, and then upload and activate the uploaded certificate, so as to achieve automatic configuration of CDN certificates. You can use the automatic timing execution script function of 1panel to execute it every month to update the certificate. It really implements a strange little trick✊✊✊.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.