Advertisement
devsaider

Yandex DDNS

Mar 2nd, 2014
1,381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. import requests
  2. import urllib2
  3. import time
  4. import threading
  5. import ConfigParser
  6.  
  7. from BeautifulSoup import BeautifulStoneSoup
  8.  
  9. def _(a, c = "MAIN"): print("[%s %s] %s"%(time.strftime("%H:%M:%S", time.localtime()), c.upper(), a))
  10.  
  11. def load_config():
  12.     config = ConfigParser.RawConfigParser()
  13.     config.read('conf.ini')
  14.  
  15.     out = []
  16.  
  17.     for section in config.sections():
  18.         timeout = config.getint(section, 'timeout')
  19.         token = config.get(section, 'token')
  20.         domain = [config.get(section, 'subdomain'), config.get(section, 'domain')]
  21.         out.append([timeout, token, domain])
  22.     return out
  23.  
  24. current = threading.local()
  25.  
  26. _('running')
  27. def request(method, data):
  28.     data['token'] = current.token
  29.     r = requests.get('https://pddimp.yandex.ru/nsapi/%s.xml'%method, params=data)
  30.     return [r.url, r.text]
  31.  
  32. def get_host_info(host):
  33.     soup = BeautifulStoneSoup(request('get_domain_records', {'domain':'nanomice.su'})[1])
  34.     if soup.contents[2].domains.error.contents[0] == 'ok':
  35.         for record in soup.contents[2].domains.response:
  36.             if record['domain'] == host:
  37.                 return [int(record['id']), record.contents[0]]
  38.     return False
  39.  
  40. def my_ip():
  41.     ret = urllib2.urlopen('https://enabledns.com/ip')
  42.     return ret.read()
  43.  
  44. def main():
  45.     conf = load_config()
  46.     for host in conf:
  47.         current.timeout, current.token, current.domain = host
  48.         host_info = get_host_info('.'.join(current.domain))
  49.         if host_info:
  50.             host_id, host_ip = host_info
  51.             current_ip = my_ip()
  52.             if host_ip != current_ip:
  53.                 _('ip changed (%s)'%' -> '.join([host_ip, current_ip]))
  54.                 soup = BeautifulStoneSoup(request('edit_a_record', {'domain':current.domain[1], 'subdomain':current.domain[0], 'record_id':host_id, 'content':current_ip})[1])
  55.                 status = soup.contents[2].domains.error.contents[0]
  56.                 if status == 'ok':
  57.                     _('successful changed ip')
  58.                 else:
  59.                     _('error : %s'%status)
  60.             else:
  61.                 _('ip not changed')
  62. if __name__ == "__main__":
  63.     while True:
  64.         main()
  65.         time.sleep(current.timeout)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement