替换上你的 Token,域名ID,记录ID等参数,就可以运行了。 跟原代码不同的是,该版本每次执行就运行一次,方便使用调度系统来进行调度
获得domain_id可以用curl
curl -k https://dnsapi.cn/Domain.List -d "login_token=xxx"
获得record_id类似
curl -k https://dnsapi.cn/Record.List -d "login_token=xxx&domain_id=xxx"
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import copy | |
import httplib | |
import socket | |
import urllib | |
import json | |
default_params = { | |
"login_token": "<token_id>,<token>", | |
"format": "json", | |
"domain_id": <domain_id>, # replace with your domain_od, can get it by API Domain.List | |
"record_id": <record_id>, # replace with your record_id, can get it by API Record.List | |
} | |
def ddns(ip): | |
params = copy.copy(default_params) | |
params.update({ | |
"value": ip, | |
"record_line": "默认", | |
"sub_domain": "home", # replace with your sub_domain | |
}) | |
headers = {"Content-type": "application/x-www-form-urlencoded", | |
"Accept": "text/json"} | |
conn = httplib.HTTPSConnection("dnsapi.cn") | |
conn.request("POST", "/Record.Ddns", urllib.urlencode(params), headers) | |
response = conn.getresponse() | |
print response.status, response.reason | |
data = response.read() | |
print data | |
conn.close() | |
return response.status == 200 | |
def getip(): | |
sock = socket.create_connection(('ns1.dnspod.net', 6666)) | |
ip = sock.recv(16) | |
sock.close() | |
return ip | |
def get_record_ip(): | |
params = copy.copy(default_params) | |
headers = {"Content-type": "application/x-www-form-urlencoded", | |
"Accept": "text/json"} | |
conn = httplib.HTTPSConnection("dnsapi.cn") | |
conn.request("POST", "/Record.Info", urllib.urlencode(params), headers) | |
response = conn.getresponse() | |
data = response.read() | |
conn.close() | |
if response.status == 200: | |
record = json.loads(data) | |
return record['record']['value'] | |
else: | |
raise Exception("error response code") | |
if __name__ == '__main__': | |
try: | |
current_ip = getip() | |
record_ip = get_record_ip() | |
print "current_ip {} and record_ip {}".format(current_ip, record_ip) | |
if current_ip != record_ip: | |
ddns(current_ip) | |
else: | |
print "record are the same, do not modify" | |
except Exception, e: | |
print e | |
pass |