• 2024-11-21
宇哥博客 后端开发 Python利用阿里云云解析实现DDNS

Python利用阿里云云解析实现DDNS

目的

远程控制家里的Windows系统电脑。

准备

阿里云域名

家里电脑所在网络有公网IP

Python环境(我安装的为版本为3.6.8)

内容

在阿里云后台https://ram.console.aliyun.com/manage/ak 获取AccessKey ID和AccessKey Secret。

安装依赖包

pip3 install aliyun-python-sdk-core-v3 
pip3 install aliyun-python-sdk-domain 
pip3 install aliyun-python-sdk-alidns 
pip3 install requests

完整代码

# coding= utf-8

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
import requests
from urllib.request import urlopen
import json
import sys
import time

#解决urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

ipv4_flag = 0  # 是否开启ipv4 ddns解析,1为开启,0为关闭
ipv6_flag = 1  # 是否开启ipv6 ddns解析,1为开启,0为关闭
accessKeyId = "XXXX"  # 将accessKeyId改成自己的accessKeyId
accessSecret = "XXXXX"  # 将accessSecret改成自己的accessSecret
domain = "ygbks.com"  # 你的主域名
name_ipv4 = "www"  # 要进行ipv4 ddns解析的子域名
name_ipv6 = "XXXX"  # 要进行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)   
    request.set_Type(Type)
    request.set_Value(Value)
    response = client.do_action_with_exception(request)

if ipv4_flag == 1:
    request = DescribeSubDomainRecordsRequest()
    request.set_accept_format('json')
    request.set_DomainName(domain)
    request.set_SubDomain(name_ipv4 + '.' + domain)
    response = client.do_action_with_exception(request)  # 获取域名解析记录列表
    domain_list = json.loads(response)  # 将返回的JSON数据转化为Python能识别的

    ip = urlopen('https://api-ipv4.ip.sb/ip').read()  # 使用IP.SB的接口获取ipv4地址
    ipv4 = str(ip, encoding='utf-8')
    print("获取到IPv4地址:%s" % ipv4)

    if domain_list['TotalCount'] == 0:
        add(domain, name_ipv4, "A", ipv4)
        print("新建域名解析成功")
    elif domain_list['TotalCount'] == 1:
        if domain_list['DomainRecords']['Record'][0]['Value'].strip() != ipv4.strip():
            update(domain_list['DomainRecords']['Record'][0]['RecordId'], name_ipv4, "A", ipv4)
            print("修改域名解析成功")
        else:   
            print("IPv4地址没变")
    elif domain_list['TotalCount'] > 1:
        from aliyunsdkalidns.request.v20150109.DeleteSubDomainRecordsRequest import DeleteSubDomainRecordsRequest
        request = DeleteSubDomainRecordsRequest()
        request.set_accept_format('json')
        request.set_DomainName(domain)   
        request.set_RR(name_ipv4)
        response = client.do_action_with_exception(request)
        add(domain, name_ipv4, "A", ipv4)
        print("修改域名解析成功")

if ipv6_flag == 1:
    print('----------ipv6----------')
    
    request = DescribeSubDomainRecordsRequest()
    request.set_accept_format('json')
    request.set_DomainName(domain)
    request.set_SubDomain(name_ipv6 + '.' + domain)
    response = client.do_action_with_exception(request)  # 获取域名解析记录列表
    domain_list = json.loads(response)  # 将返回的JSON数据转化为Python能识别的

    ip = urlopen('https://api-ipv6.ip.sb/ip').read()  #使用IP.SB的接口获取ipv6地址
    ipv6 = str(ip, encoding='utf-8')

    #ipv6=json.load(urlopen('https://jsonip.com'))['ip'] #也可以使用这个获取
    
    print("获取到IPv6地址:%s" % ipv6)

    #sys.exit()
    
    if domain_list['TotalCount'] == 0:
        add(domain, name_ipv6, "AAAA", ipv6)
        print("新建域名解析成功")
    elif domain_list['TotalCount'] == 1:
        if domain_list['DomainRecords']['Record'][0]['Value'].strip() != ipv6.strip():
            update(domain_list['DomainRecords']['Record'][0]['RecordId'], name_ipv6, "AAAA", ipv6)
            print("修改域名解析成功")
        else:   
            print("IPv6地址没变")
    elif domain_list['TotalCount'] > 1:
        from aliyunsdkalidns.request.v20150109.DeleteSubDomainRecordsRequest import DeleteSubDomainRecordsRequest
        request = DeleteSubDomainRecordsRequest()
        request.set_accept_format('json')
        request.set_DomainName(domain)
        request.set_RR(name_ipv6)   
        response = client.do_action_with_exception(request)
        add(domain, name_ipv6, "AAAA", ipv6)
        print("修改域名解析成功")

    time.sleep(5) #5秒后

我用的是ipv6,保存文件 aliyunddns.py

添加到任务计划,设定每X分钟执行一次。

运行效果:

代码部分转自:https://www.cnblogs.com/huangshengpeng/p/13859839.html

本文来自网络,不代表本站立场,转载请注明出处。https://www.ygbks.com/1559.html

发表回复

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

返回顶部