import os
import sys
from datetime import datetime
from alibabacloud_alidns20150109.client import Client as DNSClient
from alibabacloud_tea_openapi import models as api_models
from alibabacloud_alidns20150109 import models as dns_models
import requests
class DDNS:
domain = 'abc.com' #你的域名
rr = 'www' #子域名
def __init__(self) -> None:
pass
def initialization(self) -> DNSClient:
AccessKeyId = 'xxxxxx' # 阿里云自行获取
AccessKeySecret = 'xxxxxxx' # 阿里云自行获取
api_conf = api_models.Config(access_key_id=AccessKeyId,access_key_secret=AccessKeySecret)
return DNSClient(api_conf)
def getIP(self) ->str:
#这里需要自备一个获取ip地址的页面,自编代码来读取页面中的纯ip地址 如 66:220:232:111
#我的页面返回内容是[123:22:111:66]形式,所以代码是去掉左右两个[]
return requests.get('一个能获取当前主机ip地址的页面').text[1:-1]
def domain_recored(self,client:DNSClient,domain:str,rr:str):
req = dns_models.DescribeDomainRecordsRequest(direction=None,domain_name=domain,rrkey_word=rr,type='A')
resp = client.describe_domain_records(req)
record = resp.body.domain_records.record[0]
return record
def update_record(self,client:DNSClient,rr,rid,ip):
req = dns_models.UpdateDomainRecordRequest(rr=rr,record_id=rid,value=ip,type='A')
resp = client.update_domain_record(req)
def log(self,message):
cur_date = datetime.now()
path = os.path.dirname(__file__) #macOS不加路径文件会创建在 “/user/用户名/” 下
fname = path+'/'+cur_date.strftime("%Y-%m-%d") + '.log'
message = cur_date.strftime("[%Y-%m-%d %H:%M:%S] ") + message +"\n"
with open(file=fname,mode='a',encoding='utf-8') as file:
file.writelines(message)
file.flush()
file.close()
print(message)
def main(self):
client = self.initialization()
record = self.domain_recored(client,self.domain,self.rr)
local = self.getIP()
log_str = 'local='+ curip + ' record='+record.value
if local != record.value:
#更新记录,写日志
self.update_record(client,self.rr,record.record_id,local)
record_new = self.domain_recored(client,self.domain,self.rr)
log_str += ' update record '+record_new.value
self.log(log_str)
if __name__ == '__main__':
ddns = DDNS()
ddns.main()
命名为alidddns.py完结
需要加入crontab
#添加ddns到mac crontab 每两分钟同步一次
*/2 * * * * /usr/local/bin/python3 /Users/tophalo/ddns/aliddns.py
Crontab使用方法看我另一篇避坑文章