让代码更简单

当前位置:代码狗 > 资源教程 > 资源分享 > 正文

群辉Python实现阿里云域名DDNS动态解析

重要:本文最后更新于2021-09-02 16:13:57,某些文章具有时效性,若有错误或已失效,请在下方留言或联系代码狗

前两天发现一直开着机的黑群晖还有一半性能没用上,于是给安装上了centos7并且装上宝塔,成为一台调试机器。我的网络是中国移动的动态内网地址,但是分配了公网ipv6地址,于是打算使用阿里云动态域名解析实现ip变化仍能访问,然后宝塔里面的阿里云动态域名解析插件居然还要收费5元!不能忍,于是动手写了一个小脚本实现此功能,支持ipv4与ipv6。

Python代码运行环境仅支持Python3.X,没有的可以参考这篇文章进行安装。Centos7.X升级默认Python到3.X并安装pip3扩展管理

首先使用pip工具安装阿里云python版的sdk,以及其它的支持库

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

要通过api接口操作阿里云账号,必须使用 accessKeyIdaccessSecret ,这两个东西可以在阿里云控制台个人中心直接获取。

然后抄代码

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
import json

class Aliyun:
def __init__(self,accessKeyId,accessSecret,region,domain,ipv4name,ipv6name):
self.accessKeyId=accessKeyId
self.accessSecret=accessSecret
self.ipv4name=ipv4name
self.ipv6name=ipv6name
self.domain=domain
self.client=AcsClient(accessKeyId, accessSecret, region)


def update(self,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 = self.client.do_action_with_exception(request)


def add(self,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 = self.client.do_action_with_exception(request)

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

def TS(self,text):
curtime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
TS_URL = "企业微信推送地址"
data={
"lx":"textcard",
"title":"阿里云DDNS自动解析",
"desc":'<div class="gray">'+curtime+'</div> <div class="highlight">'+text+'</div>',
"url":"https://www.daimadog.com",
"more":"更多"
}
r=requests.post(TS_URL,data=data)
print(r.text)
def getip(self,isipv4,isipv6):
if isipv4==True:
r = requests.get('https://api-ipv4.ip.sb/ip')
if r.status_code==requests.codes.ok:
ipv4=r.text
with open("/www/Python/aliyun/ipv4.log","r") as fr:
oldipv4=fr.read()
#print(oldipv4)
fr.close()
if oldipv4==ipv4:
print("IPV4本地对比无变化:"+oldipv4)
else:
with open("/www/Python/aliyun/ipv4.log","w+") as f:
f.write(ipv4)
f.close()
print("IPV4本地对比发生变化:"+ipv4)
domain_list=self.getdomainlist(self.domain,"A",self.ipv4name)
if domain_list['TotalCount'] == 0:
self.add(self.domain, self.ipv4name, "A", ipv4)
print("新建域名IPV4解析成功")
self.TS("新建域名IPV4解析成功:"+ipv4)
elif domain_list['TotalCount'] == 1:
if domain_list['DomainRecords']['Record'][0]['Value'].strip() != ipv4.strip():
self.update(domain_list['DomainRecords']['Record'][0]['RecordId'], self.ipv4name, "A", ipv4)
print("修改域名IPV4解析成功")
self.TS("修改域名IPV4解析成功:"+ipv4)
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(self.domain)
request.set_RR(self.ipv4name)
request.set_Type("A") 
response = self.client.do_action_with_exception(request)
self.add(self.domain, self.ipv4name, "A", ipv4)
print("修改域名IPV4解析成功") 
self.TS("修改域名IPV4解析成功:"+ipv4)
else:
print("ipv4地址查询失败")
self.TS("ipv4地址查询失败,请及时检查!")
if isipv6==True: 
r = requests.get('https://api-ipv6.ip.sb/ip')
if r.status_code==requests.codes.ok:
ipv6=r.text
with open("/www/Python/aliyun/ipv6.log","r") as fr:
oldipv6=fr.read()
fr.close()
#print(oldipv6)
if oldipv6==ipv6:
print("IPV6本地对比无变化:"+oldipv6)
else:
with open("/www/Python/aliyun/ipv6.log","w+") as f:
f.write(ipv6)
print("IPV6本地对比发生变化:"+ipv6)
f.close()
domain_list=self.getdomainlist(self.domain,"AAAA",self.ipv6name)
if domain_list['TotalCount'] == 0:
self.add(self.domain, self.ipv6name, "AAAA", ipv6)
print("新建域名解析成功")
self.TS("新建域名解析成功:"+ipv6)
elif domain_list['TotalCount'] == 1:
if domain_list['DomainRecords']['Record'][0]['Value'].strip() != ipv6.strip():
self.update(domain_list['DomainRecords']['Record'][0]['RecordId'], self.ipv6name, "AAAA", ipv6)
print("修改域名IPV6解析成功")
self.TS("修改域名IPV6解析成功:"+ipv6)
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(self.domain)
request.set_RR(self.ipv6name)
request.set_Type("AAAA") 
response = self.client.do_action_with_exception(request)
self.add(self.domain, self.ipv6name, "AAAA", ipv6)
print("修改域名IPV6解析成功")
self.TS("修改域名IPV6解析成功:"+ipv6)
else:
print("ipv6地址查询失败")
self.TS("ipv6地址查询失败,请及时检查!")



aliyun=Aliyun("你的accessKeyId","你的accessSecret","区域","一级域名","ipv4二级域名前缀","ipv6二级域名前缀")
aliyun.getip(False,True)#第一个是ipv4,第二个ipv6,true开启,false关闭

上面的代码好像格式有点乱,python对格式要求比较严格,如果你不懂python,可以直接下载附件。

保存上面的代码,将里面需要修改的地方改成你的,然后在宝塔面板中添加计划任务.

群辉Python实现阿里云域名DDNS动态解析

群辉Python实现阿里云域名DDNS动态解析

手动点击执行后看看日志

群辉Python实现阿里云域名DDNS动态解析

群辉Python实现阿里云域名DDNS动态解析

注意:请手动修改代码中的ip地址保存文件路径!否则可能会报错!

/www/Python/aliyun/ipv4.log
/www/Python/aliyun/ipv6.log

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏

评论 抢沙发

×

请作者吃根烤肠!

支付宝