Last active
April 5, 2022 09:13
-
-
Save HHim8826/01a917b77357dd3c9b0c28f2ff7fa56d to your computer and use it in GitHub Desktop.
cf-ddns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #-*- coding: utf-8 -* | |
| import requests | |
| class ddns: | |
| def __init__(self): | |
| self.auth_email = "abc@abc.com" # cloudflare email | |
| self.auth_key= "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" #https://dash.cloudflare.com/profile/api-tokens Global API Key | |
| self.zone_name= "abc.xyz" | |
| self.record_name= "xx.abc.xyz" | |
| self.headers = { | |
| 'X-Auth-Email' : self.auth_email, | |
| 'X-Auth-Key': self.auth_key, | |
| 'Content-Type': 'application/json' | |
| } | |
| self.zone_identifier = self.get_zone() | |
| self.zone_identifier_target = self.get_record()['id'] | |
| # with open('ip.txt',mode='r',encoding='utf-8') as f: | |
| # self.old_ip = f.read() | |
| def get_ip(self): | |
| req = requests.get('http://ipv4.icanhazip.com') | |
| return req.text.strip() | |
| def get_zone(self): | |
| url = 'https://api.cloudflare.com/client/v4/zones' | |
| payload ={ | |
| 'name' : self.zone_name | |
| } | |
| req = requests.get(url,headers=self.headers,params=payload) | |
| # pprint(req.json()) | |
| # with open('a.json',mode='w') as f: | |
| # f.write(json.dumps(req.json())) | |
| return req.json()['result'][0]['id'] | |
| def get_record(self): | |
| url = f'https://api.cloudflare.com/client/v4/zones/{self.zone_identifier}/dns_records' | |
| payload ={ | |
| 'name' : self.record_name | |
| } | |
| req = requests.get(url,headers=self.headers,params=payload) | |
| return req.json()['result'][0] | |
| def put_ip(self,ip): | |
| url = f'https://api.cloudflare.com/client/v4/zones/{self.zone_identifier}/dns_records/{self.zone_identifier_target}' | |
| data = { | |
| "id" : self.zone_identifier, | |
| "type" : "A", | |
| "name" : self.record_name, | |
| "content" : ip | |
| } | |
| req = requests.put(url,headers=self.headers,json=data) | |
| return req | |
| def main(self): | |
| self.ip = self.get_ip() | |
| self.record = self.get_record() | |
| # self.get_zone() | |
| if self.record['content'] == self.ip: | |
| exit(f'Record {self.record_name} IP no changed') | |
| else: | |
| self.put_ip(self.ip) | |
| self.record_name = self.record['name'] | |
| print(f'Record : {self.record_name}') | |
| print(f'IP changed to: {self.ip}') | |
| if __name__ == '__main__': | |
| ddns = ddns() | |
| ddns.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment