配置值 去 cloudflare网站的域名管理处查看,因为 aws云主机的ip附件只可以操作Ipv4的记录,所以这个脚本也是针对动态更新Ipv4记录,也就是A记录。
#!/usr/bin/env python
# coding=utf-8
# 更新! 更新! 没有写创建,所以你先要去cloudflare网站创建一个A纪录,
# API 参考地址
# https://developers.cloudflare.com/api/operations/dns-records-for-a-zone-update-dns-record
import json
import requests
import os
import sys
import datetime
# Cloudflare 配置文件
email = ''
zone_id = ''
api_key = ''
name = ''
ttl = '60'
record_id = '' # cloudfalre id
def write_log(line_info):
t = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if isinstance(line_info, str):
with open('log4.txt', 'a', encoding='utf-8') as f:
f.write(t + ' ' + line_info + ' \n')
f.close()
else:
with open('log4.txt', 'a', encoding='utf-8') as f:
f.write(t + ' 未知类型数据写入记录,写入失败 ' + ' \n')
f.close()
def get_internet_ipv4():
public_url = 'http://ipinfo.io/json'
res = requests.get(public_url).text
#print(res)
resJson = json.loads(res)
ip = resJson['ip']
return ip
# 获取ip地址并 测试
ipaddr = get_internet_ipv4()
#print("您当前的外网Ipv4地址是: ", ipaddr)
headers={
"Content-Type": "application/json; charset=UTF-8",
"X-Auth-Email": email,
"X-Auth-Key": api_key
}
data = {
"type": "A",
"name": name,
"content": ipaddr,
"ttl": ttl,
"proxied": False
}
# 获取域名解析详情,判断是否需要更新IP
# GET https://api.cloudflare.com/client/v4/zones/{zone_identifier}/dns_records/{identifier}
def get_current_ip():
geturl = 'https://api.cloudflare.com/client/v4/zones/' + zone_id + '/dns_records/' + record_id
det = requests.get(geturl, headers=headers).text
#print(det)
detJson = json.loads(det)
if (detJson['success']) == True:
#curr_det_json = detJson['result']
logtxt = "检查域名解析IP " + detJson['result']['name'] + " ==> " + detJson['result']['content']
write_log(logtxt)
#print("域名当前指向IP ", detJson['result']['name'], "=>", detJson['result']['content'])
else:
logtxt = "检查域名解析IP 失败 ,请检查网络和配置"
write_log(logtxt)
#print("获取域名详细信息失败,请检查网络和配置……")
return detJson['result']['content']
# 更新dns方法 PUT # https://api.cloudflare.com/client/v4/zones/{zone_identifier}/dns_records/{identifier}
def update_dns_record():
updateurl = 'https://api.cloudflare.com/client/v4/zones/' + zone_id + '/dns_records/' + record_id
reTxt = requests.put(updateurl, data=json.dumps(data), headers=headers).text
print(reTxt)
result = json.loads(reTxt)
if(result['success']) == False:
return False
return True
currentIp = get_current_ip()
if(currentIp == ipaddr):
print("ip指向正确,不需要更新")
logtxt = "ip指向正确,取消更新"
write_log(logtxt)
#sys.exit(0)
else:
if update_dns_record():
print("Ipv4更新成功: ", cfg['name'], "==>", ipaddr)
logtxt = "域名动态更新成功 " + cfg['name'] + "==>" + ipaddr
write_log(logtxt)
else:
print("很失败,请检查配置参数等等")
write_log("The script failed, please check config and internet ")
sys.exit(0)如果需要更新ipv6的地址,需要修改获取IpV6本机地址的函数