Skip to content

Instantly share code, notes, and snippets.

@kennyz
Last active August 26, 2019 15:35
Show Gist options
  • Save kennyz/0afc809baabd8223fddf to your computer and use it in GitHub Desktop.
Save kennyz/0afc809baabd8223fddf to your computer and use it in GitHub Desktop.
Dnspod on Linux

说明

如果你想在自己家里搭建一个网站折腾,可以看看本文。由于家庭宽带IP地址总是发生变化,因此需要需要使用动态DNS服务,目前在linux下最好用的还是dnspod,简洁、接口开放、稳定。

准备

在dnspod.cn上注册一个帐号,是免费的,很好用。

写脚本

在其他网站上找到的别人的各种语言的更新dns代码都是只能支持一个子域名,很奇怪,难道支持多域名是我个性化的需求吗?而且dnspod的api每次是覆盖更新,所以不能使用多个脚本来更新。

于是把代码做了一些调整支持同时更新多个子域名。现在只需要修改以下代码行即可增加多个子域名: ddns_domains = {"*":1111111, "@":222222, "www":3333333};

* 标识泛域名解析,可以解析你所有的子域名,如 aaa.kongwu.net aaa.kongwu.net …xxx.kongwu.net @ 表示默认域名,比如 kongwu.net 这是我比较喜欢的用法

这里的1111111表示的是这个子域名的record_id, 如何获得record_id呢?

curl -k https://dnsapi.cn/Domain.List -d "login_email=dnspod_user&login_password=dnspod_pwd"

在xml文件中找到domain_id domain_id = 12345678

curl -k https://dnsapi.cn/Record.List -d "login_email=dnspod_user&login_password=dnspod_pwd&domain_id=12345678"

然后在显示的xml中找到record_id对应的值。

最后,见下面的代码[https://gist.github.com/kennyz/0afc809baabd8223fddf#file-pypod-py] 。

运行脚本

用以下命令运行脚本 /usr/bin/python /home/pi/bin/pypod.py >/home/pi/pypod.log

也可以把它加入到crontab中去(每5分钟自动更新一次):

*/5 * * * * /usr/bin/python /home/pi/bin/pypod.py > /home/pi/logs/pypod.log

好了,大功告成,到dnspod的界面上看你更新过的ip吧

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import httplib, urllib
import socket
import time
import sys
#replace with your sub_domain and your record_id, which can get it by API Record.List
ddns_domains = {"*":1111111, "@":222222};
params = dict(
login_email="dnspod_username", # replace with your email
login_password="dnspod_password", # replace with your password
format="json",
domain_id=1234567, # replace with your domain_od, can get it by API Domain.List
record_line="默认",
)
current_ip = None
def ddns(ip,domain):
params.update(dict(value=ip,sub_domain=domain,record_id=ddns_domains[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)
print params;
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
if __name__ == '__main__':
try:
ip = getip()
print ip
if current_ip != ip:
for domain in ddns_domains:
ddns(ip, domain);
current = ip
#if ddns(ip):
# current_ip = ip
except Exception, e:
print e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment