python
复制代码
import json
import requests
import subprocess
import re
import time
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
def ReturnRecordId(Domain, SubDomain):
"""
获取指定记录的RecordId
:param Domain: 主域名
:param SubDomain: 待修改的子域
:return: RecordId 或错误码
"""
try:
cred = credential.Credential(SecretId, SecretKey) # 凭证
httpProfile = HttpProfile()
httpProfile.endpoint = "dnspod.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = dnspod_client.DnspodClient(cred, "", clientProfile)
req = models.DescribeRecordListRequest()
params = {"Domain": Domain}
req.from_json_string(json.dumps(params))
resp = client.DescribeRecordList(req)
for record in resp.RecordList:
if record.Name == SubDomain:
return record.RecordId
# print("未找到对应的记录值,请先创建相应的主机记录!")
return -2
except TencentCloudSDKException:
# print("获取域名的记录列表失败,请重试!")
return -1
def ModifyDynamicDNS(RecordId, Domain, SubDomain, Ip):
"""
动态域名解析API
:param RecordId: 待修改记录ID
:param Domain: 主域名
:param SubDomain: 子域名
:param Ip: IP地址
:return: 操作成功返回1,否则返回0
"""
try:
cred = credential.Credential(SecretId, SecretKey)
httpProfile = HttpProfile()
httpProfile.endpoint = "dnspod.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = dnspod_client.DnspodClient(cred, "", clientProfile)
req = models.ModifyDynamicDNSRequest()
params = {
"Domain": Domain,
"SubDomain": SubDomain,
"RecordId": RecordId,
"RecordLine": "默认",
"Value": Ip
}
req.from_json_string(json.dumps(params))
resp = client.ModifyDynamicDNS(req)
# if str(RecordId) in resp.to_json_string():
# print("更新成功!")
return 1
except TencentCloudSDKException:
return 0
def get_global_ipv6_address():
# 适用于Windows的命令
command = "ipconfig"
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
stdout, stderr = process.communicate()
# 解析ipconfig输出查找IPv6地址
ipv6_addresses = re.findall(r"IPv6 地址 . . . . . . . . . . . . : ([\da-fA-F:]+)", stdout)
# 过滤掉本地链接地址
global_ipv6_addresses = [addr for addr in ipv6_addresses if not addr.startswith("fe80:")]
return global_ipv6_addresses[0]
if __name__ == "__main__":
SecretId = "xxx" # 腾讯云账户API密钥ID
SecretKey = "xxx" # 腾讯云账户API密钥Key
Domain = "xxx.xxx" # 主域名
SubDomain = "xxx" # 指定要修改的子域名
interval = 600 # 每10分钟检查一次IP
RecordId = ReturnRecordId(Domain=Domain, SubDomain=SubDomain)
if RecordId < 0:
exit()
CurrentIP = get_global_ipv6_address()
res = ModifyDynamicDNS(RecordId=RecordId, Domain=Domain, SubDomain=SubDomain, Ip=CurrentIP)
# if res:
# print(f'IP成功更新!IPV6:{CurrentIP}')
# else:
# print('动态域名解析API出问题了')