第一步:拥有阿里云域名,设置阿里云域名管理账号

转载自:https://www.jianshu.com/p/b8e01206f58c
1.1 登录阿里云控制台
1.2 在产品与服务中搜“访问控制”

1.3 创建新用户,只勾选编程访问。
这里要记住AccessKeyID和AccessKey Secret,后面需要用到。

1.4 添加DNS管理权限
找到AliyunDNSFullAccess权限,并添加。

第二步:新建加载运行python文件

参考:https://blog.zeruns.tech/archives/507.html
实际使用时会遇到请求超时等情况.
作出了一些代码的修改:(目前只修改了ipv4,ipv6自行参考修改~)
1.在超时时不再请求。
2.断网重连
1.环境安装:
python环境

2.需要安装的库:

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

3.新建aliddns.py文件,修改配置:

accessKeyId = "xxx"  # 将accessKeyId改成自己的accessKeyId
accessSecret = "xxx"  # 将accessSecret改成自己的accessSecret
domain = "xxx.cn"  # 你的主域名
name_ipv4 = "xxx"  # 要进行ipv4 ddns解析的子域名
name_ipv6 = ""  # 要进行ipv6 ddns解析的子域名

4.用cmd运行aliddns.py文件
改进后的aliddns.py文件
添加了ping IP的方法get_external_ip(),用来防止ip检测的网站挂掉。

from ast import For
from operator import truediv
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 subprocess
from datetime import datetime
from threading import Timer
# import socketipv4_flag = 1  # 是否开启ipv4 ddns解析,1为开启,0为关闭
ipv6_flag = 0  # 是否开启ipv6 ddns解析,1为开启,0为关闭
accessKeyId = "xxx"  # 将accessKeyId改成自己的accessKeyId
accessSecret = "xxx"  # 将accessSecret改成自己的accessSecret
domain = "xxx.cn"  # 你的主域名
name_ipv4 = "xxx"  # 要进行ipv4 ddns解析的子域名
name_ipv6 = ""  # 要进行ipv6 ddns解析的子域名print_str = []client = AcsClient(accessKeyId, accessSecret, 'cn-hangzhou')def update(RecordId, RR, Type, Value):  # 修改域名解析记录from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequestrequest = 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 AddDomainRecordRequestrequest = 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)print_str.append("%s"%response)def ping(): #ping百度查看网络状态,断网重新执行方法try:html = requests.get("https://www.aliyun.com",timeout=10)except:print_str.append("未获取ping通")return 0return 1# return1 = subprocess.call('ping www.baidu.com', shell = False)# if return1:#   return 0# else:#   return 1def get_external_ip():#使用try 捕捉异常try:#ip = urlopen(url='https://api-ipv4.ip.sb/ip',timeout=10.0).read()  # 使用IP.SB的接口获取ipv4地址,这个网址崩溃过ip = urlopen(url='http://ifconfig.me',timeout=10.0).read()  # 获取ipv4地址except:print_str.append("未获取到ip地址")# try:#   ip = urlopen(url='https://api4.ipify.org',timeout=10.0).read()  # 获取ipv4地址# except:#   ip = requests.get('https://ident.me').text.strip()#   return ip# return ipreturn ipdef setDnsv4():if ipv4_flag == 1 & ping()==1:try:request = DescribeSubDomainRecordsRequest()request.set_accept_format('json')request.set_DomainName(domain)request.set_SubDomain(name_ipv4 + '.' + domain)request.set_Type("A")response = client.do_action_with_exception(request)  # 获取域名解析记录列表# print_str.append("获取域名解析记录列表:%s" % response)domain_list = json.loads(response)  # 将返回的JSON数据转化为Python能识别的# 加上timeout参数,可判断阿里云是否阻止访问#获取IPV4地址ip =get_external_ip()# print_str.append("获取到ip地址:%s" % ip)ipv4 = str(ip, encoding='utf-8')# print("获取到IPv4地址:%s" % ipv4)print_str.append("获取到IPv4地址:%s" % ipv4)if domain_list['TotalCount'] == 0:add(domain, name_ipv4, "A", ipv4)# print("新建域名解析成功")print_str.append("新建域名解析成功")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("修改域名解析成功")print_str.append("修改域名解析成功")else:  # https://blog.zeruns.tech# print("IPv4地址没变")print_str.append("IPv4地址没变")elif domain_list['TotalCount'] > 1:from aliyunsdkalidns.request.v20150109.DeleteSubDomainRecordsRequest import DeleteSubDomainRecordsRequestrequest = DeleteSubDomainRecordsRequest()request.set_accept_format('json')request.set_DomainName(domain) request.set_RR(name_ipv4)request.set_Type("A") response = client.do_action_with_exception(request)add(domain, name_ipv4, "A", ipv4)# print("修改域名解析成功")print_str.append("修改域名解析成功")except Exception as err:print_str.append(err.__class__.__name__) # 错误类型print_str.append(err) # 错误明细# print("联网失败")print_str.append("联网失败")else:# print("联网失败")print_str.append("联网失败")def setDnsv6():if ipv6_flag == 1 & ping()==1:request = DescribeSubDomainRecordsRequest()request.set_accept_format('json')request.set_DomainName(domain)request.set_SubDomain(name_ipv6 + '.' + domain)request.set_Type("AAAA")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')print("获取到IPv6地址:%s" % ipv6)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 DeleteSubDomainRecordsRequestrequest = DeleteSubDomainRecordsRequest()request.set_accept_format('json')request.set_DomainName(domain)request.set_RR(name_ipv6)  # https://blog.zeruns.techrequest.set_Type("AAAA") response = client.do_action_with_exception(request)add(domain, name_ipv6, "AAAA", ipv6)print("修改域名解析成功")# 打印时间函数
def timeSet(inc):print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))setDnsv4()t = Timer(inc, timeSet, (inc,))t.start()
# 5s
timeSet(60)

以前的aliddns.py文件(此代码不稳定,请看已改进代码块)

from ast import For
from operator import truediv
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 subprocess
from datetime import datetime
from threading import Timer
# import socketipv4_flag = 1  # 是否开启ipv4 ddns解析,1为开启,0为关闭
ipv6_flag = 0  # 是否开启ipv6 ddns解析,1为开启,0为关闭
accessKeyId = "xxx"  # 将accessKeyId改成自己的accessKeyId
accessSecret = "xxx"  # 将accessSecret改成自己的accessSecret
domain = "xxx.cn"  # 你的主域名
name_ipv4 = "xxx"  # 要进行ipv4 ddns解析的子域名
name_ipv6 = ""  # 要进行ipv6 ddns解析的子域名client = AcsClient(accessKeyId, accessSecret, 'cn-hangzhou')def update(RecordId, RR, Type, Value):  # 修改域名解析记录from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequestrequest = 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 AddDomainRecordRequestrequest = 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)def ping(): #ping百度查看网络状态,断网重新执行方法try:html = requests.get("http://www.baidu.com",timeout=2)except:return 0return 1# return1 = subprocess.call('ping www.baidu.com', shell = False)# if return1:#   return 0# else:#   return 1def setDnsv4():if ipv4_flag == 1 & ping()==1:try:request = DescribeSubDomainRecordsRequest()request.set_accept_format('json')request.set_DomainName(domain)request.set_SubDomain(name_ipv4 + '.' + domain)request.set_Type("A")response = client.do_action_with_exception(request)  # 获取域名解析记录列表domain_list = json.loads(response)  # 将返回的JSON数据转化为Python能识别的# 加上timeout参数,可判断阿里云是否阻止访问ip = urlopen(url='https://api-ipv4.ip.sb/ip',timeout=10.0).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:  # https://blog.zeruns.techprint("IPv4地址没变")elif domain_list['TotalCount'] > 1:from aliyunsdkalidns.request.v20150109.DeleteSubDomainRecordsRequest import DeleteSubDomainRecordsRequestrequest = DeleteSubDomainRecordsRequest()request.set_accept_format('json')request.set_DomainName(domain) request.set_RR(name_ipv4)request.set_Type("A") response = client.do_action_with_exception(request)add(domain, name_ipv4, "A", ipv4)print("修改域名解析成功")except:print("联网失败")else:print("联网失败")def setDnsv6():if ipv6_flag == 1 & ping()==1:request = DescribeSubDomainRecordsRequest()request.set_accept_format('json')request.set_DomainName(domain)request.set_SubDomain(name_ipv6 + '.' + domain)request.set_Type("AAAA")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')print("获取到IPv6地址:%s" % ipv6)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 DeleteSubDomainRecordsRequestrequest = DeleteSubDomainRecordsRequest()request.set_accept_format('json')request.set_DomainName(domain)request.set_RR(name_ipv6)  # https://blog.zeruns.techrequest.set_Type("AAAA") response = client.do_action_with_exception(request)add(domain, name_ipv6, "AAAA", ipv6)print("修改域名解析成功")# 打印时间函数
def timeSet(inc):print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))setDnsv4()t = Timer(inc, timeSet, (inc,))t.start()
# 5s
timeSet(60)

转载时请标明文章中的出处和引用!

【DDNS】Python实现阿里云域名DDNS相关推荐

  1. python实现阿里云域名绑定动态IP

    一般家庭网络的公网IP都是不固定的,而我又想通过域名来访问自己服务器上的应用,也就是说:需要通过将域名绑定到动态IP上来实现这个需求.于是乎,我开始探索实现的技术方案.通过在网上查阅一系列的资料后,发 ...

  2. aliddns ipv6_Python实现阿里云域名DDNS支持ipv4和ipv6-阿里云开发者社区

    前言 然后你的IP必须是公网IP,不然解析了也没用. 本文章讲怎样通过阿里云的SDK来添加修改域名解析,检查本机IP与解析的IP是否一致,不一致自动修改解析,达到动态解析的目的,主要用于家庭宽带这些动 ...

  3. 阿里云、腾讯云----域名DDNS云解析到动态IP

    DDNS(Dynamic Domain Name Server,动态域名服务)是将用户的动态IP地址映射到一个固定的域名解析服务上. 本教程详细介绍如何使用阿里云Alibaba Cloud SDK f ...

  4. 实现阿里云域名的DDNS

    实现阿里云域名的DDNS 目前现状与痛点 我们在使用ddns的时候会不会遇到这样的问题:路由器只支持指定的域名服务提供商或者是指定的域名,比如我的华为路由器就只支持花生壳: 我想看到这篇文章的小伙伴们 ...

  5. 群辉默认DDNS功能解析阿里云-自定义服务商

    前言 前不久买了个群辉NAS发现群辉DDNS不能解析阿里云,后来找了很多教程都是部署Docker或使用其他平台转发一下,然而这些平台还要注册,我就在想我自己可不可以实现不需要注册就可以使用的DDNS, ...

  6. 阿里云域名 动态ip绑定 python方案

    阿里云域名 动态ip绑定 python方案 一.配置config.json 二.代码 三.打包执行 思路:阿里云提供dns域名解析api,查出外网ip,定时更新域名解析. 一.配置config.jso ...

  7. 如何利用阿里云域名远程访问家中群辉NAS(Docker容器)上的calibre、halo博客?

    看前备注:作者也是小白,只是在自己的摸索中积攒了一点经验,分享给大家.不能保证100%的正确,欢迎大家讨论分享. 我的博客(会同步更新的):陌路遥的博客 文作者:陌路遥/欢迎转载 如何利用阿里云域名远 ...

  8. 阿里云域名网站https申请,ssl续签设置图文教程

    网站https现如今是标配,基本上各大域名服务商都有免费的https,免费ssl证书可供申请,同时也有不少免费ssl证书提供商可申请使用,不过需要注意这样一个ssl证书到期的问题,比如本渣渣最近遇到的 ...

  9. python调用阿里云sdk

    python调用阿里云sdk python阿里SDK 安装阿里云 Python SDK 使用Python SDK 导入包 实例Action python阿里SDK 安装阿里云 Python SDK 完 ...

最新文章

  1. 在js中获取input中的value
  2. Boost::context模块fiber的斐波那契测试程序
  3. jax-rs jax-ws_创建一个简单的JAX-RS MessageBodyWriter
  4. [html] html和html5有什么区别呢?
  5. 1盒子刷webpad_拉宽带送的盒子也有春天:一招解放各种束缚限制
  6. java的自动类型转换和强制类型转换
  7. SQL Server 2000中数据库质疑的恢复方法
  8. ckpt下载 deeplabv3_Ubantu下 用deeplabV3+训练自己的数据集 你可能遇到的所有坑都在这了...
  9. delphi连接access数据库的步骤(详细教程)
  10. 单尺度retinex算法 matlab,单尺度retinex算法
  11. 浏览器flash/html5视频播放如何倍速(Enounce MySpeed)
  12. 好的编码习惯是一场代码驱邪仪式
  13. value too long for type character varying(32)
  14. 旅行商问题与蚁群算法
  15. tooth的用法_tooth的复数和用法例句
  16. Photoshop 2021 22.4.3 精简版
  17. Studing Day2 - python基础2
  18. 2018最新苹果公司开发者账号设置税务
  19. DeepLab V1模型原理
  20. EasyClick 易点云测 IOS版自动化测试工具

热门文章

  1. Ubuntu16.04安装youtub_dl
  2. 2018苹果开发者技术支持新规
  3. VMware与宿主机文件夹共享、虚拟机磁盘映射
  4. 【CV/Matlab系列】基于图像处理的苹果质量检测和分级系统【含Matlab源码】
  5. 作业5 - 团队展示
  6. 大数数字读法 unsigned long long
  7. 最新易企秀 微场景制作源码 易企秀去版权源码 带几百套模板
  8. linux通过文件修改密码,如何通过Linux系统来修改密码
  9. ObjectARX C++自定义实体
  10. springboot+vue校园食堂网上订餐系统-带商家idea