python版本簡易阿里雲ddns

光和环發表於2024-03-08

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使用方法看我另一篇避坑文章

相關文章