Last active
May 1, 2019 00:35
-
-
Save wyyqyl/954c442bd8169f0ac058 to your computer and use it in GitHub Desktop.
Setup DDNS with DNSPOD API
This file contains hidden or 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/env python | |
#-*- coding:utf-8 -*- | |
import socket | |
import fcntl | |
import struct | |
import json | |
import httplib, urllib | |
params = dict( | |
login_email="", | |
login_password="", | |
format="json", | |
domain_id=, | |
record_id= | |
) | |
def ddns(ip): | |
ddns_params = params.copy() | |
ddns_params.update(dict(sub_domain="@", record_line="默认", value=ip)) | |
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/json"} | |
conn = httplib.HTTPSConnection("dnsapi.cn") | |
conn.request("POST", "/Record.Ddns", urllib.urlencode(ddns_params), headers) | |
response = conn.getresponse() | |
data = response.read() | |
conn.close() | |
print data | |
def get_ip_address(ifname): | |
try: | |
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) | |
except IOError: | |
print 'Interface', ifname, 'doesn\'t exist!' | |
return '' | |
return ip | |
def get_localip(): | |
ip = get_ip_address('eth0') | |
if len(ip) == 0: | |
ip = get_ip_address('wlan0') | |
return ip | |
def get_remoteip(): | |
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/json"} | |
conn = httplib.HTTPSConnection("dnsapi.cn") | |
conn.request("POST", "/Record.Info", urllib.urlencode(params), headers) | |
response = conn.getresponse() | |
raw_data = response.read() | |
conn.close() | |
data = json.loads(raw_data) | |
if data['status']['code'] != '1': | |
print raw_data | |
return '' | |
return data['record']['value'] | |
def main(): | |
rip = get_remoteip() | |
if len(rip) == 0: | |
print 'Failed to fetch remote ip addr, quit' | |
return | |
lip = get_localip() | |
if len(lip) == 0: | |
print 'Failed to get local ip addr, quit' | |
return | |
if lip == rip: | |
print 'The same ip addr, quit' | |
return | |
ddns(lip) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment