Purpose

为避免在核心服务器使用Oray发布的富客户端而引入许多不必要的管理风险、安装依赖的X Window库,按照Oray官方的HTTP API,实现了轻量级的DDNS查询更新Client.

文档地址: 点击这里

Source

# oray.py
# coding: utf8

MIN_INTERVAL = 5
CHECK_IP_URL = 'http://ddns.oray.com/checkip'
UPDATE_ORAY_DDNS_URL = 'http://ddns.oray.com/ph/update'


import sys
import urllib2
import re

oray_code_dict = {
	'good': u'更新成功,域名的IP地址已经更新',
	'nochg': u'更新成功,但没有改变IP',
	'notfqdn': u'未有激活花生壳的域名',
	'nohost': u'域名不存在或未激活花生壳',
	'abuse': u'请求失败,频繁请求或验证失败时会出现',
	'badauth': u'验证失败,用户名或密码错误',
	'badagent': u'请求的User-Agent不合法',
	'!donator': u'表示此功能需要付费用户才能使用,如https',
	'911': u'系统错误',
	}

class OrayHttpAuthHandler(urllib2.HTTPBasicAuthHandler):
	rx = re.compile('([^ \t]+)[ \t]+([^ \t]+)[ \t]+'
		'realm=["\'](.*?)["\']', re.I)
	
	def http_error_auth_reqed(self, authreq, host, req, headers):
		authreq = headers.get(authreq, None)
		if self.retried > 5:
			raise HTTPError(
				req.get_full_url(), 
				401, 
				'basic auth failed', 
				headers, None
				)
		else:
			self.retried += 1

		if authreq:
			mo = self.rx.search(authreq)
			if mo:
				scheme, quote, realm = mo.groups()
				if scheme.lower() == 'basic':
					response = self.retry_http_basic_auth(
							host,
							req, 
							realm
							)
					if response and response.code != 401:
						self.retried = 0
					return response



def _get_text_from_node(nodelist):
	rc = []
	for node in nodelist:
		if node.nodeType == node.TEXT_NODE:
			rc.append(node.data)
	return ''.join(rc)

	

def get_ip(url):
	import urllib2
	f = urllib2.urlopen(url)
	t = f.read().strip()

	from xml.dom import minidom
	root = minidom.parseString(t)
	node = root.getElementsByTagName('body')[0]

	body = _get_text_from_node(node.childNodes)
	ip = body.split(':')[1].strip()

	return ip

def update_ddns(baseurl, user, passwd, hostname):

	import urllib2,urllib

	data = {
		'hostname': hostname,
	}


	params = urllib.urlencode(data)
	url = '%s?%s' %( baseurl, params)

	auth_handler = OrayHttpAuthHandler()
	auth_handler.add_password(
				realm='DDNS',
				uri=baseurl,
				user=user,
				passwd=passwd
				)

	opener = urllib2.build_opener(auth_handler)
	
	f = opener.open(url)
	t = f.read().strip()
	status, ip = t.split()

	return status, ip

def Main(options):
	if options.interval < MIN_INTERVAL :
		print >>sys.stderr, \
			'interval must greater than %d' % MIN_INTERVAL
		sys.exit(1)

	import time

	interval = options.interval * 60
	last_get_ip = u''
	while True:
		try:
			ip = get_ip(CHECK_IP_URL)
			if ip == last_get_ip:
				continue

			print >>sys.stdout, 'ip have change: %s' % ip

			status, t = update_ddns(UPDATE_ORAY_DDNS_URL, 
				options.user,
				options.passwd,
				options.hostname
				)
			
			msg = oray_code_dict[status]

			print 'status, msg: ', status, msg
			if status not in ('good', 'nochg'):
				continue

			last_get_ip = ip

		except Exception, e:
			import traceback, StringIO
			print >>sys.stderr, 'occer unhandle exception: \n'
			traceback.print_exc(file=sys.stderr)
			if isinstance(e, urllib2.HTTPError):
				print >>sys.stderr, ' ', e.hdrs
			
		finally:
			time.sleep(interval)


if __name__ == '__main__':
	from optparse import OptionParser

	parser = OptionParser()
	parser.add_option('--user', dest='user',
			help='oray account')
	parser.add_option('--passwd', dest='passwd',
			help='oray accout password')
	parser.add_option('-t', dest='interval', type=int,
			help=u'隔多久更新一次域名, 单位分钟, 最小为%d' % MIN_INTERVAL)
	parser.add_option('--hostname', dest='hostname',
			help='oray account hostname list, use , separate')

	parser.add_option('--log', dest='logfile',
			help='log file')

	parser.set_defaults(interval=5)
	(options, args) = parser.parse_args()

	Main(options)

Usage

python oray.py --user oray_user --passwd oray_password --hostname oray_dynamic_domian