Skip to content

Instantly share code, notes, and snippets.

@qiyuangong
Last active February 28, 2023 22:57
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save qiyuangong/9318624 to your computer and use it in GitHub Desktop.
Save qiyuangong/9318624 to your computer and use it in GitHub Desktop.

DDNS_DNSPOD

###功能 基于DNSPOD (www.dnspod.com)的动态域名解析脚本:

适用于有域名在手,并且托管到dnspod的童鞋。

###原理 基于dnspod提供的api,提交信息。 如果IP地址没有改变,则不处理;如果改变了则提交新的IP地址。

###引用申明 本脚本基于roy@leadnt.com的原始dnspod脚本,修改了IP地址获取部分。

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import urllib2,urllib,json,socket,commands
# Based on roy@leadnt.com code
class DNS:
#Dnspod账户
_dnspod_user = 'dnspod_username'
#Dnspod密码
_dnspod_pwd = 'dnspod_password'
#Dnspod主域名,注意:是你注册的域名
_domain = 'your domain'
#子域名,如www,如果要使用根域名,用@
_sub_domain = 'your subdomain'
def getIP(self):
"""get local IP based on socket.
Try to connect baidu.com, then getsockname"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('baidu.com', 0))
return s.getsockname()[0]
def getlocalIP(self, intf='eth0'):
"""get local IP from eth0.
If VPN is connected, getIP will get assigned VPN client IP.
So we need to get IP from eth0 or eth1"""
intf_ip = commands.getoutput("ip address show dev " + intf).split()
intf_ip = intf_ip[intf_ip.index('inet') + 1].split('/')[0]
return intf_ip
def api_call(self,api,data):
try:
api = 'https://dnsapi.cn/' + api
data['login_email'] = self._dnspod_user
data['login_password'] = self._dnspod_pwd
data['format'] ='json'
data['lang'] = 'cn'
data['error_on_empty'] = 'no'
data = urllib.urlencode(data)
req = urllib2.Request(api,data,
headers = {
'UserAgent' : 'LocalDomains/1.0.0',
'Content-Type':'application/x-www-form-urlencoded;text/html; charset=utf8',
})
res = urllib2.urlopen(req)
html = res.read()
results = json.loads(html)
return results
except Exception as e:
print e
def main(self):
ip = self.getIP()
if '192.168' in ip:
ip = self.getlocalIP()
dinfo = self.api_call('domain.info',{'domain' : self._domain})
domainId = dinfo['domain']['id']
rs = self.api_call('record.list',
{
'domain_id': domainId,
'offset' :'0',
'length' : '1',
'sub_domain' : self._sub_domain
})
if rs['info']['record_total'] == 0:
self.api_call('record.create',
{
'domain_id' : domainId,
'sub_domain' : self._sub_domain,
'record_type' : 'A',
'record_line' : '默认',
'value' : ip,
'ttl' : '3600'
})
print 'Success.'
else:
if rs['records'][0]['value'].strip() != ip.strip():
self.api_call('record.modify',
{
'domain_id' : domainId,
'record_id' : rs['records'][0]['id'],
'sub_domain' : self._sub_domain,
'record_type' : 'A',
'record_line' : '默认',
'value' : ip
})
else:
print 'Success.'
if __name__ == '__main__':
d = DNS();
d.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment