请注意:
此客户端代码仅限于运行在直接连接在互联网的设备上(一般来说就是网关路由器)
此客户端需要linux运行环境
此客户端需要python语言解释器执行(一般来说,各种linux发行版均默认自带python解释器)
使用此程序,需要掌握以下技能:shell基本操作, linux文本编辑器(vi/nano)基本操作
安装方法:
复制以下源代码并保存为dnspod.py
使用您自己的设置更改源代码中的变量(请注意代码中的注释)
将dnspod.py保存到linux服务器中/bin(使用winscp或者在vi/nano中粘贴)
执行以下命令:
chmod +x /bin/dnspod.py
5. 执行以下命令进行测试
/bin/dnspod.py
6. 执行以下命令检查程序输出
tail /var/log/dnspod.log
7. 请确认程序输出了 “IP address changed to xx.xx.xx.xx, dnspod DDNS updated” 即可
8. 执行以下命令打开linux中的计划任务描述文件
crontab -e
9. 在cron的任务文件描述中加入以下一行内容并保存,此后每隔10分钟将自动执行此程序一次
*/10 * * * * /bin/dnspod.py
10. 完成!
#!/user/bin/env python
#coding=utf-8
import urllib, urllib2, json
import socket, struct, fcntl
import sys, os, time
url = "https://dnsapi.cn/Record.Ddns"
# 使用你自己的设置更改以下内容
account = "account@email.com" # 你在dnspod.cn注册的邮件地址
password = "password" # 你在dnspod.cn注册密码
domain_id = "12345678" # 你的域名id (如何获取请查看本文最下方)
sub_domain = "hostname" # 你要更新的主机头名,例如 hostname.mydomain.com
record_id = "12345678" # 此主机头名对应的记录id (如何获取请查看本文最下方)
record_line = "默认" # dnspod.cn中为此记录指定的线路
wan_ifname = "ppp0" # 连接 Internet 的网卡设备名(对于拨号上网的路由器来说,一般为ppp0)
# 使用你自己的设置更改以上内容
prev_file = "/dev/shm/wan.prev"
log_file = "/var/log/dnspod.log"
def get_ipaddress(interface):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915,
struct.pack("256s", interface[:15])
)[20:24]
)
def print_log(text):
log = open(log_file, "a")
timestamp = time.strftime(‘%Y-%m-%d %H:%M:%S‘)
log.write(timestamp + " | " + text + "\n")
log.close()
values = {
"login_email": account,
"login_password": password,
"domain_id": domain_id,
"sub_domain": sub_domain,
"record_id": record_id,
"record_line": record_line,
"format": "json"
}
changed = False
current_ip = get_ipaddress(wan_ifname)
prev_ip = ""
if not os.path.exists(prev_file):
prev = open(prev_file, "a")
prev.write(current_ip)
prev.close()
changed = True
else:
prev = open(prev_file, "r")
prev_ip = prev.readline().strip()
prev.close()
if prev_ip != current_ip:
prev = open(prev_file, "w")
prev.write(current_ip)
prev.close()
changed = True
if changed:
print_log("IP address changed to " + current_ip)
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
content = response.read()
myinfo = json.loads(content)
if myinfo["status"]["code"] == "1": print_log("dnspod DDNS updated")
# print_log("IP address not changed yet")本文出自 “iPlay IT” 博客,转载请与作者联系!
原文地址:http://iplayit.blog.51cto.com/7753603/1575600