一 、简介
DDNS(动态域名服务)是将用户的动态公网ip地址映射到一个固定的域名解析服务上,用户每次连接网络的时候客户端程序就会通过信息传递把该主机的动态公网ip地址推送到服务商的域名解析上,服务商提供dns服务进行域名解析
二、环境
- 域名(以aliyun为例)
- linux主机
三、准备
1、购买域名
本文是基于aliyun平台做的实验
2、添加解析记录
3、浏览器按F12 进入开发者模式获取recordId值
4、4、获取accessKeyId、accesssKeySecret值
四、编写脚本
脚本是基于python 环境写的
1、安装python aliyun模块
pip3 install aliyun-python-sdk-core
pip3 install aliyun-python-sdk-alidns
pip3 install requests
2、脚本
脚本参考:https://blog.51cto.com/u_15060510/4373806
import json,datetime
from json import load
from urllib.request import urlopen
from aliyunsdkcore.client import AcsClient
from aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest
from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest
i = str(datetime.datetime.now())
newip = load(urlopen('https://api.ipify.org/?format=json'))['ip']
AccessKey_ID = '<accessKeyId>' # 填入accessKeyId
Access_Key_Secret = '<accesssKeySecret>' # 填入accesssKeySecret
region_id = "<recordId>" # 填入recordId
DomainName = '<域名>' # 填入域名(如:baidu.com)
RR = '<二级域名>' # 填入二级域名(如:www)
DomainType = 'A'
UpdateDomain = 'Auto_Lines'
def AliAccessKey(id,Secret,region):
client = AcsClient(id, Secret, region)
return client
def GetDNSRecordId(client,DomainName):
request = DescribeDomainRecordsRequest()
request.set_accept_format('json')
request.set_DomainName(DomainName)
response = client.do_action_with_exception(request)
json_data = json.loads(str(response, encoding='utf-8'))
for RecordId in json_data['DomainRecords']['Record']:
if RR == RecordId['RR']:
return RecordId['RecordId']
def UpdateDomainRecord(client,RecordId):
try:
request = UpdateDomainRecordRequest()
request.set_accept_format('json')
request.set_Value(newip)
request.set_Type(DomainType)
request.set_RR(RR)
request.set_RecordId(RecordId)
client.do_action_with_exception(request)
print("域名:" + DomainName + " 主机:" + RR + " 记录类型:" + DomainType + " 记录值:" + newip)
except Exception as e:
print(i + ' DNS已经更新')
def main():
client = AliAccessKey(AccessKey_ID,Access_Key_Secret,region_id)
RecordId = GetDNSRecordId(client,DomainName)
UpdateDomainRecord(client,RecordId)
if __name__ == "__main__" :
main()