Re DNS every minute with python
import requests
import json
response_ip = requests.get('<https://ifconfig.me/ip>')
new_ip = ""
if (response_ip.status_code == 200):
new_ip = response_ip.text
data = [
# example1.com
{
"zone_id":"...",
"api_token":"...",
"dns":[]
},
# example2.com
{
"zone_id":"...",
"api_token":"...",
"dns": [
{
"id": "...",
"name": "admin.neighborsoft.com"
},
{
"id": "...",
"name": "test.neighborsoft.com"
},
{
"id": "...",
"name": "toeicapi.neighborsoft.com"
},
{
"id": "...",
"name": "toeic.neighborsoft.com"
}
]
},
# example3.dev
{
"zone_id":"...",
"api_token":"...",
"dns":[]
},
]
FILE_NAME = "/home/pi/shared/ip.txt"
old_ip = ""
with open(FILE_NAME) as f:
for line in f:
old_ip = line.strip()
print(old_ip, new_ip)
break
if old_ip != new_ip:
for i in range(len(data)):
zone_id = data[i]["zone_id"]
my_headers = {'Authorization' : 'Bearer {}'.format(data[i]["api_token"])}
results_dns = data[i]["dns"]
if len(results_dns) == 0:
response_dns = requests.get('<https://api.cloudflare.com/client/v4/zones/{}/dns_records?type=A>'.format(zone_id), headers=my_headers)
# print(response_dns.text)
results_dns = json.loads(response_dns.text)["result"]
for record in results_dns:
# print(record['id'])
url = '<https://api.cloudflare.com/client/v4/zones/{}/dns_records/{}>'.format(zone_id, record['id'])
# print(url)
results_dns_update = requests.patch(url, json = {"content": new_ip}, headers=my_headers)
# print(results_dns_update)
if (response_ip.status_code == 200):
print("updated {}".format(record['name']))
else:
print("updated fail!")
with open(FILE_NAME, "w") as file:
file.writelines(new_ip)
file.close()
else:
print("IP is collected")
<aside> ⛔ "dns":[] = update ทุก DNS
</aside>
Run with crontab
* * * * * /usr/bin/python3 /home/pi/shared/updatedns.py >> /home/pi/shared/log_dns.txt
<aside> ⛔ อย่าลืม check python → which python3
</aside>