[Python] 纯文本查看 复制代码
from pathlib import Path
from threading import Timer
import requests
from loguru import logger
from retrying import retry
ip_url = "http://www.3322.org/dyndns/getip"
recordid_url = "https://dnsapi.cn/Record.List"
ddns_url = "https://dnsapi.cn/Record.Ddns"
ip_list = []
def init_parameter():
"""初始化参数"""
global logger
path = lambda filename:Path(__file__).parent.joinpath(filename)
logger.add(path('ddns_record.log'))
@retry(tries=5)
def requestToFunction(url,method='GET',data=None):
"""请求函数,返回结果文本"""
if method == 'GET':
res = requests.get(url,timeout=10)
res.encoding = 'utf8'
return res.text
else:
res = requests.post(url,data=data,timeout=10)
res.encoding = 'utf8'
return res.text
def get_record_id(recordid_url,domain_id,login_token):
"""获取record_id"""
formdata = {
'domain_id': domain_id,
'login_token': login_token
}
text = requestToFunction(recordid_url,method='POST',data=formdata)
res_json = eval(text)
try:
record_id = res_json.get('records')[0]['id']
return record_id
except Exception as e:
logger.error(f'获取record_id失败,失败原因{e}')
def ddns_record(ddns_url,domain_id,login_token,ip,record_id):
"""更新ddns"""
formdata = {
'domain_id': domain_id,
'login_token': login_token,
'record_line': '默认',
'record_line_id': '10=1',
'value': ip,
'record_id': record_id
}
text = requestToFunction(ddns_url,method='POST',data=formdata)
res_json = eval(text)
if (res_json['status']['code'] == '1'):
logger.info(res_json['status']['message'], '域名解析已更改为' + ip)
def main(domain_id,login_token):
"""主逻辑,检测IP变化并更新ddns"""
record_id = get_record_id(recordid_url,domain_id,login_token)
assert record_id
ip = requestToFunction(ip_url)
if ip_list is not None:
on_a = ip_list.pop(0)
if ip != on_a:
ddns_record(ddns_url,domain_id,login_token,ip,record_id)
else:
logger.info('ip 未更改')
else:
ddns_record(ddns_url,domain_id,login_token,ip,record_id)
ip_list.append(ip)
def cycle_perform(times,domain_id,login_token):
"""循环检测函数"""
main(domain_id,login_token)
t = Timer(times,cycle_perform,args=(times,domain_id,login_token)) # 每隔15分钟检测一次
t.start()
if __name__ == '__main__':
init_parameter()
domain_id,login_token = "","" # 填入从[url=http://www.ddnspad.com]www.ddnspad.com[/url]上获取的domain_id,login_token
cycle_perform(900,domain_id,login_token)