-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
71 lines (55 loc) · 1.99 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python3
import CloudFlare
import json
import requests
import time
config = json.load(open("config.json"))
def get_public_ip(): # sourcery skip: raise-specific-error
endpoint = "https://ipinfo.io/json"
response = requests.get(endpoint, verify=True)
if response.status_code != 200:
raise Exception(f"Status: {response.status_code}")
data = response.json()
return data["ip"]
class CloudflarePatcher:
def __init__(self, account) -> None:
self.cf = CloudFlare.CloudFlare(account["email"], account["api_key"])
self.account = account
self.zone_id = account["zone_id"]
def load_variables(self):
variables = {
variable: globals()[f"get_{variable}"]()
for variable in self.account["variables"]
}
print("New Variables:", variables)
return variables
def parse_record(self, record):
record_str = json.dumps(record)
variables = self.load_variables()
for variable in variables:
record_str = record_str.replace("{{" + variable + "}}", variables[variable])
return json.loads(record_str)
def patch_dns_records(self):
for dns_record in self.account["dns_records"]:
record = self.parse_record(dns_record["value"])
try:
self.cf.zones.dns_records.patch(
self.zone_id, dns_record["id"], data=record
)
dns_record["value"] = record
print(f"Updated {dns_record}")
except Exception as e:
exit(f"/zones.dns_records.patch {dns_record} - {e}")
def main():
last_ip = None
while True:
curr_ip = get_public_ip()
if curr_ip != last_ip:
for account in config:
patcher = CloudflarePatcher(account)
patcher.patch_dns_records()
last_ip = curr_ip
print("Sleeping for 15 minutes")
time.sleep(60 * 15)
if __name__ == "__main__":
main()