Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Bluscream
Last active January 5, 2021 09:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bluscream/c0f794186d0236e072b1826987c9390e to your computer and use it in GitHub Desktop.
Save Bluscream/c0f794186d0236e072b1826987c9390e to your computer and use it in GitHub Desktop.
Cloudflare Failover System for free
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Origin: https://gist.github.com/Bluscream/c0f794186d0236e072b1826987c9390e
from json import dumps, loads
from requests import request
from random import choice
from socket import socket, AF_INET, SOCK_STREAM
domain = "" # Your tld
zone_id = "" # Your zoneid
records = { # records that need to be changed
"": "ts.%s"%domain, # "zoneid": "domain",
"": "ts3.%s"%domain
}
failovers = [ # failovers to choose from
".%s"%domain, # "domain",
".%s"%domain
]
check = (next(iter(records.values())), 30033) # host and port to check if failover needed
payload = {
"type":"CNAME",
"ttl":120,
"proxied": False
}
headers = {
'X-Auth-Email': "", # your cloudflare email
'X-Auth-Key': "", # your cloudflare api key
'Content-Type': "application/json",
'Cache-Control': "no-cache"
}
def check_port(host=check[0], port=check[1]):
sock = socket(AF_INET, SOCK_STREAM)
result = sock.connect_ex((host, port))
if result == 0:
print("Checked {}:{} > Port is open.".format(host,port))
return True
elif result == 10061:
print("Checked {}:{} > Port is closed!".format(host,port))
elif result == 10060:
print("Checked {}:{} > Connection timed out!".format(host,port))
else:
print("Checked {}:{} > Unknown Error ({})!".format(host,port,result))
return False
def get_current():
response = request("GET", "https://api.cloudflare.com/client/v4/zones/%s/dns_records/%s" % (zone_id, next(iter(records.keys()))), headers=headers)
return loads(response.text)["result"]["content"]
def update_records():
current = get_current()
_failovers = failovers.copy()
_failovers.remove(current)
payload["content"] = choice(_failovers)
if not check_port(payload["content"]):
update_records()
return
for record_id, name in records.items():
payload["name"] = name
response = request("PUT", "https://api.cloudflare.com/client/v4/zones/%s/dns_records/%s" % (zone_id, record_id), data=dumps(payload), headers=headers)
print(loads(response.text))
if not check_port():
update_records()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment