Erning.write()

Reloading

Dynamic DNS-DIY

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/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)