zhoji 发表于 2022-11-18 23:37:56

[Python 转载] ddnspod 自动更新ddns

对ddns pod进行重写,新的代码条理清晰,便于理解,有兴趣的可以学习一下(注:没测试,逻辑上没问题,如果有问题可以自己改源码),保存为pyw可以后台执行
原来代码:DDNS_DNSPOD 亲测可用 - 『编程语言区』 - 吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

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')['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 = "","" # 填入从www.ddnspad.com上获取的domain_id,login_token
    cycle_perform(900,domain_id,login_token)
页: [1]
查看完整版本: [Python 转载] ddnspod 自动更新ddns