如何通过阿里云实现动态域名解析DDNS的方法

前言

该脚本的代码大部分是参考自阿里云的官方帮助文档。
1, 脚本语言使用的是python, 我个人只是了解python,没有太深入的知识功底
2, 脚本代码我会尽量详细地添加注释说明,有问题欢迎留言交流,但回复可能不会那么及时。

前置条件

1、域名是在阿里云购买的 (我的域名本身就是阿里云买的,其他的域名我没有测试过)
2、地址必须是公网地址,不然加了解析也没有用 (这个不用多加解释了)

安装阿里云sdk

需要安装三个sdk库,一个是阿里云核心sdk库,一个是阿里云域名sdk库,一个是dns库
阿里云核心sdk库:pip install aliyun-python-sdk-core
阿里云域名sdk库:pip install aliyun-python-sdk-domain
阿里云dnssdk库:pip install aliyun-python-sdk-alidns
说明:
1, 目前官方文档上说的是需要安装前两个sdk库,但我实测确定还需要第三个库!
2, 如果你使用的是ubuntu系统,并且同时有python2/python3和pip2/pip3,安装时前面的命令请写清楚版本,特别是pip。 我的系统pip默认是2.x,使用pip install xxx 命令安装的库无效,使用 pip3 install xxx 才成功(如果知道如何随意切换python和pip版本,请留言告知,感谢)。

脚本的具体功能

1, 获取外网ip地址
2,获取域名解析记录
3,新增域名解析记录
3,更新域名解析记录
4,删除域名解析记录 (并不建议将该功能添加在实际脚本中)
5,批量操作,如果记录不存在则添加记录,存在则更新记录

脚本代码

#!/usr/bin/env python
#coding=utf-8

# 加载核心sdk
from aliyunsdkcore.client import acsclient
from aliyunsdkcore.acs_exception.exceptions import clientexception
from aliyunsdkcore.acs_exception.exceptions import serverexception

# 加载获取 、 新增、 更新、 删除接口
from aliyunsdkalidns.request.v20150109 import describesubdomainrecordsrequest, adddomainrecordrequest, updatedomainrecordrequest, deletedomainrecordrequest

# 加载内置模块
import json,urllib

# accesskey 和 secret 建议使用 ram 子账户的 key 和 secret 增加安全性
id = 'xxxxxxx'
secret = 'xxxxxx'

# 地区节点 可选地区取决于你的阿里云帐号等级,普通用户只有四个,分别是杭州、上海、深圳、河北,具体参考官网api
regionid = 'cn-hangzhou'

# 配置认证信息
client = acsclient(id, secret, regionid)

# 设置主域名
domainname = 'example.com'

# 子域名列表 列表参数可根据实际需求增加或减少值
subdomainlist = ['a', 'b', 'c']

# 获取外网ip  三个地址返回的ip地址格式各不相同,3322 的是最纯净的格式, 备选1为 json格式 备选2 为curl方式获取 两个备选地址都需要对获取值作进一步处理才能使用
def getip():
  # 备选地址: 1, http://pv.sohu.com/cityjson?ie=utf-8  2,curl -l tool.lu/ip
  with urllib.request.urlopen('http://www.3322.org/dyndns/getip') as response:
    html = response.read()
    ip = str(html, encoding='utf-8').replace("\n", "")
  return ip

# 查询记录
def getdomaininfo(subdomain):
  request = describesubdomainrecordsrequest.describesubdomainrecordsrequest()
  request.set_accept_format('json')

  # 设置要查询的记录类型为 a记录  官网支持a / cname / mx / aaaa / txt / ns / srv / caa / url隐性(显性)转发 如果有需要可将该值配置为参数传入
  request.set_type("a")

  # 指定查记的域名 格式为 'test.example.com'
  request.set_subdomain(subdomain)

  response = client.do_action_with_exception(request)
  response = str(response, encoding='utf-8')

  # 将获取到的记录转换成json对象并返回
  return json.loads(response)

# 新增记录 (默认都设置为a记录,通过配置set_type可设置为其他记录)
def adddomainrecord(client,value,rr,domainname):
  request = adddomainrecordrequest.adddomainrecordrequest()
  request.set_accept_format('json')

  # request.set_priority('1') # mx 记录时的必选参数
  request.set_ttl('600')    # 可选值的范围取决于你的阿里云账户等级,免费版为 600 - 86400 单位为秒 
  request.set_value(value)   # 新增的 ip 地址
  request.set_type('a')    # 记录类型
  request.set_rr(rr)      # 子域名名称 
  request.set_domainname(domainname) #主域名

  # 获取记录信息,返回信息中包含 totalcount 字段,表示获取到的记录条数 0 表示没有记录, 其他数字为多少表示有多少条相同记录,正常有记录的值应该为1,如果值大于1则应该检查是不是重复添加了相同的记录
  response = client.do_action_with_exception(request)
  response = str(response, encoding='utf-8')
  relsult = json.loads(response)
  return relsult

# 更新记录
def updatedomainrecord(client,value,rr,record_id):
  request = updatedomainrecordrequest.updatedomainrecordrequest()
  request.set_accept_format('json')

  # request.set_priority('1')
  request.set_ttl('600')
  request.set_value(value) # 新的ip地址
  request.set_type('a')
  request.set_rr(rr)
  request.set_recordid(record_id) # 更新记录需要指定 record_id ,该字段为记录的唯一标识,可以在获取方法的返回信息中得到该字段的值

  response = client.do_action_with_exception(request)
  response = str(response, encoding='utf-8')
  return response

# 删除记录
def deldomainrecord(client,subdomain):
  info = getdomaininfo(subdomain)
  if info['totalcount'] == 0:
    print('没有相关的记录信息,删除失败!')
  elif info["totalcount"] == 1:
    print('准备删除记录')
    request = deletedomainrecordrequest.deletedomainrecordrequest()
    request.set_accept_format('json')

    record_id = info["domainrecords"]["record"][0]["recordid"]
    request.set_recordid(record_id) # 删除记录需要指定 record_id ,该字段为记录的唯一标识,可以在获取方法的返回信息中得到该字段的值
    result = client.do_action_with_exception(request)
    print('删除成功,返回信息:')
    print(result)
  else:
    # 正常不应该有多条相同的记录,如果存在这种情况,应该手动去网站检查核实是否有操作失误
    print("存在多个相同子域名解析记录值,请核查后再操作!")

# 有记录则更新,没有记录则新增
def setdomainrecord(client,value,rr,domainname):
  info = getdomaininfo(rr + '.' + domainname)
  if info['totalcount'] == 0:
    print('准备添加新记录')
    add_result = adddomainrecord(client,value,rr,domainname)
    print(add_result)
  elif info["totalcount"] == 1:
    print('准备更新已有记录')
    record_id = info["domainrecords"]["record"][0]["recordid"]
    cur_ip = getip()
    old_ip = info["domainrecords"]["record"][0]["value"]
    if cur_ip == old_ip:
      print ("新ip与原ip相同,无法更新!")
    else:
      update_result = updatedomainrecord(client,value,rr,record_id)
      print('更新成功,返回信息:')
      print(update_result)
  else:
    # 正常不应该有多条相同的记录,如果存在这种情况,应该手动去网站检查核实是否有操作失误
    print("存在多个相同子域名解析记录值,请核查删除后再操作!")


ip = getip()

# 循环子域名列表进行批量操作
for x in subdomainlist:
  setdomainrecord(client,ip,x,domainname)

# 删除记录测试
# deldomainrecord(client,'b.jsoner.com')

# 新增或更新记录测试
# setdomainrecord(client,'192.168.3.222','a',domainname)

# 获取记录测试
# print (getdomaininfo(domainname, 'y'))

# 批量获取记录测试
# for x in subdomainlist:
#   print (getdomaininfo(domainname, x))

# 获取外网ip地址测试
# print ('(' + getip() + ')')

可以将以上脚本保存为文件之后,通过定时任务,来实现定期自动更新ip地址,具体如何添加定时任务,系统不同,可能方法也不尽相同,这里就不多说明了。

说明

1,建议不要将删除记录添加进实际使用的脚本当中。
2,相同记录是同一个子域名的多条记录,比如 test.example.com。
脚本并没有验证记录类型,所以同一子域名下的不同类型的记录也会认为是相同记录,比如:
有两条记录分别是 test.examlpe.com 的 a 记录 和 test.examlpe.com 的 aaaa 记录,会被认为是两条相同的 test.example.com 记录
可以通过判断获取记录返回的 record_id 来实现精确匹配记录,但我没有这样的需求,也就没有花时间去写。

到此这篇关于如何通过阿里云实现动态域名解析ddns的方法的文章就介绍到这了,更多相关阿里云动态域名解析ddns内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐