【代码】阿里云DDNS python脚本

忘记了从哪里找到的,在基础功能上新增了多域名控制和开关控制,以及本机IP获取方式,重构了主函数,逻辑大概就是:通过api获取ddns的配置,修改配置,然后传回去。
有输出文本,可以建一个crontab定时执行并保存日志。

#!/usr/bin/python
# pip install aliyunsdkcore aliyun-python-sdk-alidns

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkalidns.request.v20150109.DescribeSubDomainRecordsRequest import DescribeSubDomainRecordsRequest
from aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest
from urllib.request import urlopen
import json
import time

localtime = time.asctime(time.localtime(time.time()))
print("本地时间为 :", localtime)
ipv4_flag = 1  # 是否开启ipv4 ddns解析,1为开启,0为关闭
ipv6_flag = 1  # 是否开启ipv6 ddns解析,1为开启,0为关闭
accessKeyId = "abcdefg"  # 将accessKeyId改成自己的accessKeyId
accessSecret = "4thkfcvme50"  # 将accessSecret改成自己的accessSecret
domain = "kfcvme50.com"  # 你的主域名
name_ipv4 = ('*', '@')  # 要进行ipv4 ddns解析的子域名
name_ipv6 = ('*', '@')  # 要进行ipv6 ddns解析的子域名
client = AcsClient(accessKeyId, accessSecret, 'cn-hangzhou')


def update(RecordId, RR, Type, Value):  # 修改域名解析记录
    from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest
    request = UpdateDomainRecordRequest()
    request.set_accept_format('json')
    request.set_RecordId(RecordId)
    request.set_RR(RR)
    request.set_Type(Type)
    request.set_Value(Value)
    response = client.do_action_with_exception(request)


def add(DomainName, RR, Type, Value):  # 添加新的域名解析记录
    from aliyunsdkalidns.request.v20150109.AddDomainRecordRequest import AddDomainRecordRequest
    request = AddDomainRecordRequest()
    request.set_accept_format('json')
    request.set_DomainName(DomainName)
    request.set_RR(RR)  # https://subdomain.domain.org
    request.set_Type(Type)
    request.set_Value(Value)
    response = client.do_action_with_exception(request)


def delete(DomainName, RR, Type, Value):  # 添加新的域名解析记录
    from aliyunsdkalidns.request.v20150109.DeleteSubDomainRecordsRequest import DeleteSubDomainRecordsRequest
    request = DeleteSubDomainRecordsRequest()
    request.set_accept_format('json')
    request.set_DomainName(DomainName)
    request.set_RR(RR)  # https://subdomain.domain.org
    request.set_Type(Type)
    request.set_Value(Value)
    response = client.do_action_with_exception(request)


def get_ipv4(): # 尝试通过多个接口获取当前的IP地址
    try:
        myIPv4 = urlopen('https://4.ipw.cn', timeout=5).read()
        ipv4 = str(myIPv4, encoding='utf-8')
        return ipv4
    except:
        pass
    try:
        myIPv4 = urlopen('https://api-ipv4.ip.sb/ip', timeout=5).read()
        ipv4 = str(myIPv4, encoding='utf-8').replace("\n", "")
        return ipv4
    except:
        pass
    try:
        myIPv4 = urlopen('http://ip.42.pl/raw', timeout=5).read()
        ipv4 = str(myIPv4, encoding='utf-8').replace("\n", "")
        return ipv4
    except:
        pass
    try:
        myIPv4 = urlopen('http://ip.3322.net', timeout=5).read()
        print(myIPv4)
        ipv4 = str(myIPv4, encoding='utf-8').replace("\n", "")
        return ipv4
    except:
        pass
    return None


def get_ipv6(): # 尝试通过多个接口获取当前的IP地址
    try:
        myIPv6 = urlopen('https://6.ipw.cn', timeout=5).read()
        ipv6 = str(myIPv6, encoding='utf-8').replace("\n", "")
        return ipv6
    except:
        pass
    try:
        myIPv6 = urlopen('https://api-ipv6.ip.sb/ip', timeout=5).read()
        ipv6 = str(myIPv6, encoding='utf-8').replace("\n", "")
        return ipv6
    except:
        pass
    return None


def get_subdomain(subname, domain, type):
    request = DescribeSubDomainRecordsRequest()
    request.set_accept_format('json')
    request.set_DomainName(domain)
    request.set_SubDomain(subname + '.' + domain)
    request.set_Type(type)
    response = client.do_action_with_exception(request)  # 获取域名解析记录列表
    return json.loads(response)    # 将返回的JSON数据转化为Python能识别的


if __name__ == '__main__':
    if ipv4_flag == 1:
        ipv4 = get_ipv4()
        if (ipv4 == None):
            print("获取IPv4失败即将退出")
            exit(-1)
        print("我当前的IPv4地址为: " + ipv4)
        for subname_4 in name_ipv4:
            domain_list = get_subdomain(subname_4, domain, "A")
            if domain_list['TotalCount'] == 0:
                add(domain, subname_4, "A", ipv4)
                print("新建" + subname_4+'.'+domain+"\t域名解析成功")
            elif domain_list['TotalCount'] == 1:
                if domain_list['DomainRecords']['Record'][0]['Value'].strip() != ipv4.strip():
                    update(domain_list['DomainRecords']['Record']
                           [0]['RecordId'], subname_4, "A", ipv4)
                    print("修改" + subname_4+'.'+domain+"\t域名解析成功")
                else:  # https://subdomain.domain.org
                    print(subname_4+'.'+domain+"\t的IPv4地址没变")
            elif domain_list['TotalCount'] > 1:
                delete(domain, subname_4, 'A', ipv4)
                add(domain, subname_4, "A", ipv4)
                print("修改" + subname_4+'.'+domain+"\t域名解析成功")
    print("IPv4 处理完成")
    if ipv6_flag == 1:
        ipv6 = get_ipv6()
        if (ipv6 == None):
            print("获取IPv6失败即将退出")
            exit(-1)
        print("我当前的IPv6地址为: " + ipv6)
        for subname_6 in name_ipv6:
            domain_list = get_subdomain(subname_6, domain, "AAAA")
            if domain_list['TotalCount'] == 0:
                add(domain, subname_6, "AAAA", ipv6)
                print("新建" + subname_6+'.'+domain+"\t域名解析成功")
            elif domain_list['TotalCount'] == 1:
                if domain_list['DomainRecords']['Record'][0]['Value'].strip() != ipv6.strip():
                    update(domain_list['DomainRecords']['Record']
                           [0]['RecordId'], subname_6, "AAAA", ipv6)
                    print("修改" + subname_6+'.'+domain+"\t域名解析成功")
                else:  # https://subdomain.domain.org
                    print(subname_6+'.'+domain+"\t的IPv6地址没变")
            elif domain_list['TotalCount'] > 1:
                delete(domain, subname_6, 'AAAA', ipv6)
                add(domain, subname_6, "AAAA", ipv6)
                print("修改" + subname_6+'.'+domain+"\t域名解析成功")
    print("IPv6 处理完成")
print("程序功能完成,将退出。")

Leave a Comment

您的电子邮箱地址不会被公开。 必填项已用 * 标注