腾讯DNS修改解析Python脚本

lz
3
2025-07-13

前言

作用于早晚高峰自动切换解析,ChatGPT写的,运行很好已亲测部署使用。

我是通过青龙面板来定时执行切换两个不同解析值

如有需要自行修改对应值和应用

需要安装依赖:tencentcloud-sdk-python

# -*- coding: utf-8 -*-
import json
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.dnspod.v20210323 import dnspod_client, models

# 请替换以下信息
SecretId = "AKIDzr***aWFl6Fj0vo"
SecretKey = "mOuDJBu****iutnPp"
domain = "alcy.cc"        # 你的域名
subdomain = "www"          # 需要修改的子域名
record_type = "CNAME"      # 记录类型
record_line = "默认"       # 默认解析线路
new_record_value = "wwww.mwm.moe"  # 新的解析目标值

try:
    cred = credential.Credential(SecretId, SecretKey)
    httpProfile = HttpProfile()
    httpProfile.endpoint = "dnspod.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = dnspod_client.DnspodClient(cred, "", clientProfile)

    # 获取解析记录列表,找到 hub 子域名的记录ID
    req = models.DescribeRecordListRequest()
    params = {
        "Domain": domain,
        "Subdomain": subdomain,
        "RecordType": record_type
    }
    req.from_json_string(json.dumps(params))
    resp = client.DescribeRecordList(req)
    records = resp.RecordList

    # 查找记录ID
    record_id = None
    for record in records:
        if record.Name == subdomain and record.Type == record_type:
            record_id = record.RecordId
            break

    if not record_id:
        print("未找到指定子域名的解析记录!")
        exit(1)

    # 修改解析记录
    modify_req = models.ModifyRecordRequest()
    modify_params = {
        "Domain": domain,
        "RecordId": record_id,
        "SubDomain": subdomain,
        "RecordType": record_type,
        "RecordLine": record_line,
        "Value": new_record_value
    }
    modify_req.from_json_string(json.dumps(modify_params))
    modify_resp = client.ModifyRecord(modify_req)

    print("解析修改成功!记录ID:", modify_resp.RecordId)

except TencentCloudSDKException as err:
    print("发生错误:", err)

动物装饰