Last active
December 26, 2015 12:08
-
-
Save JerryFleming/7148360 to your computer and use it in GitHub Desktop.
Update dynamic ip address to point to your domains.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# coding: utf8 | |
# vim: ts=4 sts=4 fdm=marker | |
''' | |
%s <action> [option] | |
where action is: | |
update [force]: update dns. | |
generate [filter]: generate (filtered) dns record list for update. | |
''' | |
import httplib, urllib | |
import urllib2 | |
from cookielib import CookieJar | |
import socket | |
import time | |
import sys | |
import json | |
import re | |
# data {{{ | |
data = { | |
} | |
# data }}} | |
params = dict( | |
login_email = 'YOUR USERNAME', | |
login_password = 'YOUR PASSWORD', | |
format = 'json', | |
) | |
BASE = 'https://dnsapi.cn' | |
conn = httplib.HTTPSConnection('dnsapi.cn') | |
#conn = httplib.HTTPConnection('proxyHost', 'proxyPort') | |
headers = { # {{{ | |
'Content-type': 'application/x-www-form-urlencoded', | |
'Accept': 'text/json', | |
'UserAgent': 'PythonHttp/1.0 ([email protected])', | |
} # }}} | |
def generate(filter=None): # {{{ | |
if filter != 'generate': filter = filter.split(',') | |
else: filter = [] | |
rec = {} | |
conn.request('POST', BASE + '/Domain.List', urllib.urlencode(params), headers) | |
response = conn.getresponse() | |
for domain in json.loads(response.read())['domains']: | |
domain_id = domain['id'] | |
rec[domain_id] = [] | |
params['domain_id'] = domain_id | |
conn.request('POST', BASE + '/Record.List', urllib.urlencode(params), headers) | |
response = conn.getresponse() | |
for record in json.loads(response.read())['records']: | |
o = {'record_id': record['id'], 'sub_domain': record['name'], 'value': record['value']} | |
if filter and record['type'] not in filter: continue | |
rec[domain_id].append(o) | |
conn.close() | |
rec = json.dumps(rec, indent=4) | |
print rec | |
f = open(sys.argv[0], 'r') | |
s = f.read() | |
s = re.sub('(\n# data {{{\n)(.*)(\n# data }}}\n)', '\g<1>data = '+rec+'\g<3>', s, flags=re.DOTALL) | |
f.close() | |
f = open(sys.argv[0], 'w') | |
f.write(s) | |
f.close() | |
# }}} | |
def ddns(ip): # {{{ | |
params['record_line'] = '默认' | |
params['value'] = ip | |
for k, v in data.iteritems(): | |
params['domain_id'] = k | |
for record in v: | |
params.update(record) | |
conn.request('POST', BASE + '/Record.Ddns', urllib.urlencode(params), headers) | |
response = conn.getresponse() | |
print response.read() | |
conn.close() | |
# }}} | |
def getip(): # {{{ | |
sock = socket.create_connection(('ns1.dnspod.net', 6666), 30) | |
ip = sock.recv(16) | |
sock.close() | |
return ip | |
# }}} | |
def getrouter(): # {{{ | |
cj = CookieJar() | |
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) | |
urllib2.install_opener(opener) | |
base = 'http://192.168.1.1/' | |
data = { | |
'username': 'useradmin', | |
'password': 'cjmc5', | |
} | |
resp = opener.open(base + 'ctlogin.cmd', urllib.urlencode(data).encode()) | |
resp = opener.open(base + 'ctwaninfoall.html') | |
lines = resp.readlines() | |
resp = opener.open(base + 'ctlogout.cmd') | |
cj.clear() | |
ip = lines[45].split('/')[26] | |
return ip | |
# }}} | |
def update(force=False): # {{{ | |
f = open(sys.argv[0], 'a+') | |
now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) | |
current_ip = '' | |
end = -1 | |
lines = f.readlines() | |
while True: | |
try: | |
line = lines[end] | |
except IndexError as e: | |
current_ip = '' | |
if line.startswith('##'): | |
current_ip = '' | |
else: current_ip = line.strip().split(' ')[-1] | |
if current_ip and not re.match('(\d+\.){3}(\d+)', current_ip): | |
end -= 1 | |
else: break | |
try: | |
ip = getip() | |
#ip = getrouter() | |
if current_ip != ip: | |
ddns(ip) | |
f.write('# %s %s\n' % (now, ip)) | |
elif force: | |
ddns(ip) | |
print 'IP is updated to %s.' % ip | |
else: | |
print 'IP is already %s.' % ip | |
except Exception as e: | |
f.write('# %s %s\n' % (now, e)) | |
f.close() | |
# }}} | |
if __name__ == '__main__': | |
if len(sys.argv) == 1: print __doc__.strip() % sys.argv[0] | |
elif sys.argv[1] == 'update': update(len(sys.argv)==3) | |
elif sys.argv[1] == 'generate': generate(sys.argv[-1]) | |
##################### IPs #################################### {{{ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment