Dynamic DNS-DIY

宿舍的宽带好,写了一个简单的python脚本,自动更新域名解析到动态的IP地址,这样我就可以随时访问宿舍里的机器了。

#!/usr/bin/env python
 
import cookielib
import urllib
import urllib2
import time
import sys
 
def ddd_checkip():
    response = urllib2.urlopen("http://www.dragonsoft.net/checkip.php")
    return response.read()
 
def ddd_hello(opener):
    return opener.open("http://www.dns-diy.com/skin.aspx?skin=api")
 
def ddd_login(opener, username, password):
    request = urllib2.Request("https://www.dns-diy.com/api/login.aspx")
    params = urllib.urlencode({"username":username, 'password':password})
    request.add_data(params)
    return opener.open(request)
 
def ddd_logout(opener):
    request = urllib2.Request("http://www.dns-diy.com/api/logout.aspx?immediately=yes&invalidate=yes")
    return opener.open(request)
 
def ddd_update_rr(opener, id, name, type, data, aux, ttl):
    request = urllib2.Request("http://www.dns-diy.com/api/zone_rr_update.aspx")
    params = urllib.urlencode({"id":id, "rr_name":name, "rr_type":type, "rr_data":data, "rr_aux":aux, "rr_ttl":ttl})
    request.add_data(params)
    return opener.open(request)
 
#
#
#
 
DEBUG = 5
SLEEP_SECONDS = 600
 
USERNAME = "swanpan.com"
PASSWORD = "secure"
RR_ID    = "secure"
RR_NAME  = ""
RR_TYPE  = "A"
RR_DATA  = "127.0.0.1"
RR_AUX   = "0"
RR_TTL   = "5"
 
def ddd_process():
    if (DEBUG > 0):
        print "[%(time)s] updating %(host)s.%(zone)s (%(ip)s) ..." % \
            {"time":time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), \
            "host":RR_NAME, "zone":USERNAME, "ip":RR_DATA}
 
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
 
    response = ddd_hello(opener)
    if (DEBUG > 5):
        print "HELLO"
        print response.read()
 
    response = ddd_login(opener, USERNAME, PASSWORD)
    if (DEBUG > 5):
        print "LOGIN"
        print response.read()
 
    response = ddd_update_rr(opener, RR_ID, RR_NAME, RR_TYPE, RR_DATA, RR_AUX, RR_TTL)
    if (DEBUG > 5):
        print "UPDATE"
        print response.read()
 
    response = ddd_logout(opener)
    if (DEBUG > 5):
        print "LOGOUT"
        print response.read()
 
    if (DEBUG > 0):
        print "[%(time)s] Finished!" % \
            {"time":time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}
 
while True:
    try:
        ip = ddd_checkip()
        if (RR_DATA != ip):
            RR_DATA = ip
            ddd_process()
    except:
        if (DEBUG > 4):
            print "Unexpected error:", sys.exc_info()[0]
 
    time.sleep(SLEEP_SECONDS)