automatic-cloudflare-ddns 1.0.2__tar.gz → 1.0.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: automatic-cloudflare-ddns
3
- Version: 1.0.2
3
+ Version: 1.0.4
4
4
  Summary: A simple single-purpose python script to automatically update an A record to the current external IPv4 Address.
5
5
  Author: Bala Chandran
6
6
  Author-email: Bala Chandran <cfddns@bala.red>
@@ -10,32 +10,32 @@ Maintainer-email: Bala Chandran <cfddns@bala.red>
10
10
  Requires-Python: >=3.8
11
11
  Description-Content-Type: text/markdown
12
12
 
13
- # automatic-cloudflare-ddns
14
-
15
-
16
- Creates or updates a Cloudflare A record with the current external IPv4 address.
17
-
18
- # Installation
19
-
20
- Install using pip : `pip install automatic-cloudflare-ddns`
21
-
22
- # Usage
23
-
24
- `python -m automatic_cloudflare_ddns -A [AUTHORIZATION] -n [List of domain names to update seperated by spaces]`
25
-
26
-
27
- Add to your crontab (with `crontab -e`) or another scheduled runner
28
-
29
-
30
- ```
31
- options:
32
- -h, --help show this help message and exit
33
- -A, --authorization AUTHORIZATION *REQUIRED*
34
- -n, --names NAMES [NAMES ...] *REQUIRED*
35
- -t, --tries TRIES
36
- -v, --verbose
37
- -l, --logtofile
38
- -m, --maxlogfiles MAXLOGFILES
39
- ```
40
-
13
+ # automatic-cloudflare-ddns
14
+
15
+
16
+ Creates or updates a Cloudflare A record with the current external IPv4 address.
17
+
18
+ # Installation
19
+
20
+ Install using pip : `pip install automatic-cloudflare-ddns`
21
+
22
+ # Usage
23
+
24
+ `python -m automatic_cloudflare_ddns -A [AUTHORIZATION] -n [List of domain names to update seperated by spaces]`
25
+
26
+
27
+ Add to your crontab (with `crontab -e`) or another scheduled runner
28
+
29
+
30
+ ```
31
+ options:
32
+ -h, --help show this help message and exit
33
+ -A, --authorization AUTHORIZATION *REQUIRED*
34
+ -n, --names NAMES [NAMES ...] *REQUIRED*
35
+ -t, --tries TRIES
36
+ -v, --verbose
37
+ -l, --logtofile
38
+ -m, --maxlogfiles MAXLOGFILES
39
+ ```
40
+
41
41
  ### Your Authorization key must have permission to edit DNS Records in your zone(s) which contain the records to change.
@@ -1,29 +1,29 @@
1
- # automatic-cloudflare-ddns
2
-
3
-
4
- Creates or updates a Cloudflare A record with the current external IPv4 address.
5
-
6
- # Installation
7
-
8
- Install using pip : `pip install automatic-cloudflare-ddns`
9
-
10
- # Usage
11
-
12
- `python -m automatic_cloudflare_ddns -A [AUTHORIZATION] -n [List of domain names to update seperated by spaces]`
13
-
14
-
15
- Add to your crontab (with `crontab -e`) or another scheduled runner
16
-
17
-
18
- ```
19
- options:
20
- -h, --help show this help message and exit
21
- -A, --authorization AUTHORIZATION *REQUIRED*
22
- -n, --names NAMES [NAMES ...] *REQUIRED*
23
- -t, --tries TRIES
24
- -v, --verbose
25
- -l, --logtofile
26
- -m, --maxlogfiles MAXLOGFILES
27
- ```
28
-
1
+ # automatic-cloudflare-ddns
2
+
3
+
4
+ Creates or updates a Cloudflare A record with the current external IPv4 address.
5
+
6
+ # Installation
7
+
8
+ Install using pip : `pip install automatic-cloudflare-ddns`
9
+
10
+ # Usage
11
+
12
+ `python -m automatic_cloudflare_ddns -A [AUTHORIZATION] -n [List of domain names to update seperated by spaces]`
13
+
14
+
15
+ Add to your crontab (with `crontab -e`) or another scheduled runner
16
+
17
+
18
+ ```
19
+ options:
20
+ -h, --help show this help message and exit
21
+ -A, --authorization AUTHORIZATION *REQUIRED*
22
+ -n, --names NAMES [NAMES ...] *REQUIRED*
23
+ -t, --tries TRIES
24
+ -v, --verbose
25
+ -l, --logtofile
26
+ -m, --maxlogfiles MAXLOGFILES
27
+ ```
28
+
29
29
  ### Your Authorization key must have permission to edit DNS Records in your zone(s) which contain the records to change.
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "automatic-cloudflare-ddns"
7
- version = "1.0.2"
7
+ version = "1.0.4"
8
8
  requires-python = ">= 3.8"
9
9
  description = "A simple single-purpose python script to automatically update an A record to the current external IPv4 Address."
10
10
  readme = "README.md"
@@ -1,19 +1,19 @@
1
- [build-system]
2
- requires = ["uv_build >= 0.13, <0.14"]
3
- build-backend = "uv_build"
4
-
5
- [project]
6
- name = "automatic-cloudflare-ddns"
7
- version = "1.0.2"
8
- requires-python = ">= 3.8"
9
- description = "A simple single-purpose python script to automatically update an A record to the current external IPv4 Address."
10
- readme = "README.md"
11
- dependencies = [
12
- "requests"
13
- ]
14
- authors = [
15
- {name = "Bala Chandran", email = "cfddns@bala.red"},
16
- ]
17
- maintainers = [
18
- {name = "Bala Chandran", email = "cfddns@bala.red"},
19
- ]
1
+ [build-system]
2
+ requires = ["uv_build >= 0.13, <0.14"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "automatic-cloudflare-ddns"
7
+ version = "1.0.4"
8
+ requires-python = ">= 3.8"
9
+ description = "A simple single-purpose python script to automatically update an A record to the current external IPv4 Address."
10
+ readme = "README.md"
11
+ dependencies = [
12
+ "requests"
13
+ ]
14
+ authors = [
15
+ {name = "Bala Chandran", email = "cfddns@bala.red"},
16
+ ]
17
+ maintainers = [
18
+ {name = "Bala Chandran", email = "cfddns@bala.red"},
19
+ ]
@@ -1,211 +1,216 @@
1
- import argparse
2
- import time
3
- import json
4
- import requests
5
- import os
6
-
7
- logs = []
8
- logtofile = True
9
- maxlogfiles = 5
10
-
11
-
12
- try:
13
- parser = argparse.ArgumentParser(
14
- prog='automatic-cloudflare-ddns',
15
- description='Creates or updates a Cloudflare A record with the current external IPv4 address.'
16
- )
17
-
18
- parser.add_argument('-A', '--authorization',type=str, required=True)
19
- parser.add_argument('-n', '--names',nargs='+',required=True)
20
- parser.add_argument('-t','--tries',type=int,default=3)
21
- parser.add_argument('-v','--verbose',action='store_true',default=False)
22
- parser.add_argument('-l','--logtofile',action='store_true',default=False)
23
- parser.add_argument('-m','--maxlogfiles',type=int,default=5)
24
-
25
- args = parser.parse_args()
26
-
27
- authorization = args.authorization
28
- names = args.names
29
- tries = args.tries
30
- verbose = args.verbose
31
- logtofile = args.logtofile
32
- maxlogfiles = args.maxlogfiles-1
33
-
34
- def logger(message: str,place: str,name: str, colorid : int=39): #ignore
35
- match colorid:
36
- case 31: log_type = 'ERROR'
37
- case 32: log_type = 'SUCCESS'
38
- case 33: log_type = 'WARN'
39
- case _: log_type = 'INFO'
40
-
41
- log = f'[{time.strftime('%H:%M:%S', time.localtime())}][{place}/{log_type}][{name}]: {message}'
42
- if verbose or colorid != 39:
43
- print(f'\033[{colorid}m'+log+'\033[0m')
44
- if logtofile:
45
- logs.append(log+'\n')
46
-
47
- class main:
48
- def __init__(self, name : str, authorization : str):
49
- self.authorization = authorization
50
- self.api = 'https://api.cloudflare.com/client/v4/'
51
- self.headers ={'Authorization' : f'Bearer {self.authorization}'}
52
- self.zone_id = ''
53
- self.record_id = ''
54
- self.payload = ''
55
- self.already_matching = []
56
- self.name = name
57
- self.get_ip()
58
-
59
-
60
- def get_ip(self):
61
- place = 'Get IP'
62
- logger('Attempting to fetch IP',place,self.name)
63
- response = requests.get('https://checkip.amazonaws.com/')
64
-
65
- if response.ok:
66
- self.ip = response.content[:-1].decode('utf-8')
67
- logger(f'IP was succesfully fetched {self.ip}',place,self.name,32)
68
- return(True)
69
- logger(f'IP was not fetched status: {response.status_code}, {response.content}',place,self.name,31)
70
- return(False)
71
-
72
- def find_zone(self):
73
- place = 'Zone Finder'
74
- url = f'{self.api}/zones'
75
- name = self.name.split('.')
76
-
77
- logger('Fetching zones',place,self.name)
78
-
79
- response = requests.get(url=url,headers=self.headers)
80
-
81
- if response.ok:
82
- zones = json.loads(response.content)
83
-
84
- if zones['success']:
85
- logger('Zones fetched',place,self.name,32)
86
- for zone in zones['result']:
87
- current_name = zone['name'].split('.')
88
- domain_list = name[-len(current_name):]
89
-
90
- domain = ''
91
- for x in domain_list:
92
- domain += '.' + x
93
- domain = domain[1:]
94
-
95
-
96
- if domain == zone['name']:
97
- self.zone_id = zone['id']
98
- logger(f'Zone found {self.zone_id}',place,self.name,32)
99
- break
100
- return(True)
101
- logger('Failed to fetch zones',place,self.name,31)
102
- return(False)
103
-
104
- def find_record(self):
105
- place = 'Record Finder'
106
- url = f'{self.api}/zones/{self.zone_id}/dns_records'
107
-
108
- logger('Fetching records',place,self.name)
109
-
110
- response = requests.get(url=url,headers=self.headers)
111
-
112
-
113
- if response.ok:
114
- records = json.loads(response.content.decode('utf-8'))
115
- if records['success']:
116
- logger('Records fetched.',place,self.name,32)
117
- for record in records['result']:
118
- if record['name'] == self.name:
119
- if record['content'] == self.ip:
120
- self.already_matching.append(record['name'])
121
- logger(f'Matching record found but content already matches current IP address {self.ip}',place,self.name,33)
122
- break
123
- else:
124
- self.record_id = record['id']
125
- logger(f'Matching record found {self.record_id}',place,self.name,32)
126
- break
127
- return(True)
128
- logger('Failed to fetch records',place,self.name,31)
129
- return(False)
130
-
131
- def construct_payload(self):
132
- place = 'Payload Constructor'
133
- if not(self.ip):
134
- logger('IP address not found',place,self.name,31)
135
- self.get_ip()
136
- return(False)
137
- self.payload = {
138
- 'name': self.name,
139
- 'ttl': 1,
140
- 'type': 'A',
141
- 'content': self.ip,
142
- 'proxied': False
143
- }
144
- return(True)
145
-
146
- def create_record(self):
147
- place = 'Record Creator'
148
- url = f'{self.api}/zones/{self.zone_id}/dns_records'
149
-
150
- headers = self.headers.copy()
151
- headers['Content-Type'] = 'application/json'
152
-
153
- logger(f'Creating record {self.name} with {self.ip}',place,self.name)
154
-
155
- if self.construct_payload():
156
- response = requests.post(url, headers=headers, json=self.payload)
157
- return(response.ok)
158
- return(False)
159
-
160
- def update_record(self):
161
- place = 'Record Updater'
162
- url = f'{self.api}/zones/{self.zone_id}/dns_records/{self.record_id}'
163
-
164
- headers = self.headers.copy()
165
- headers['Content-Type'] = 'application/json'
166
-
167
- logger(f'Updating record {self.name} with {self.ip}',place,self.name)
168
- if self.construct_payload():
169
- response = requests.patch(url, headers=headers, json=self.payload)
170
- return(response.ok)
171
- return(False)
172
-
173
-
174
-
175
-
176
-
177
-
178
- for name in names:
179
- place = 'Attempter'
180
- session = main(name,authorization)
181
- for attempt in range(1,tries+1):
182
- logger(f'Attempt {attempt}/{tries}',place,name)
183
- if session.find_zone() and session.zone_id:
184
- logger(f'Zone ID {session.zone_id}',place,name)
185
- if session.find_record() and session.record_id:
186
- logger(f'Record ID {session.record_id}',place,name)
187
- if session.update_record():
188
- logger(f'Record updated with IP address {session.ip}',place,name,32)
189
- break
190
- elif name in session.already_matching:
191
- logger(f'Record already matches current IP address {session.ip}, skipping.',place,name,32)
192
- break
193
- else:
194
- if session.create_record():
195
- logger(f'Record created with IP address {session.ip}',place,name,32)
196
- break
197
- logger(f'Attempt {attempt} Failed',place,name,31)
198
- time.sleep(5)
199
- finally:
200
- if logtofile:
201
- log_files = []
202
- for file_name in os.listdir():
203
- if file_name.startswith("cf_ddns_"):
204
- log_files.append(file_name)
205
- log_files.sort(reverse=True)
206
- for log_file in log_files[maxlogfiles:]:
207
- os.remove(log_file)
208
-
209
- with open(f'cf_ddns_{int(time.time())}.log','w') as f:
210
- f.writelines(logs)
211
-
1
+ import argparse
2
+ import time
3
+ import json
4
+ import requests
5
+ import os
6
+
7
+ logs = []
8
+ logtofile = True
9
+ maxlogfiles = 5
10
+
11
+
12
+ try:
13
+ parser = argparse.ArgumentParser(
14
+ prog='automatic-cloudflare-ddns',
15
+ description='Creates or updates a Cloudflare A record with the current external IPv4 address.'
16
+ )
17
+
18
+ parser.add_argument('-A', '--authorization',type=str, required=True)
19
+ parser.add_argument('-n', '--names',nargs='+',required=True)
20
+ parser.add_argument('-t','--tries',type=int,default=3)
21
+ parser.add_argument('-v','--verbose',action='store_true',default=False)
22
+ parser.add_argument('-l','--logtofile',action='store_true',default=False)
23
+ parser.add_argument('-m','--maxlogfiles',type=int,default=5)
24
+
25
+ args = parser.parse_args()
26
+
27
+ authorization = args.authorization
28
+ names = args.names
29
+ tries = args.tries
30
+ verbose = args.verbose
31
+ logtofile = args.logtofile
32
+ maxlogfiles = args.maxlogfiles-1
33
+
34
+ def logger(message: str,place: str,name: str, colorid : int=39): #ignore
35
+ match colorid:
36
+ case 31: log_type = 'ERROR'
37
+ case 32: log_type = 'SUCCESS'
38
+ case 33: log_type = 'WARN'
39
+ case _: log_type = 'INFO'
40
+
41
+ log = f'[{time.strftime('%H:%M:%S', time.localtime())}][{place}/{log_type}][{name}]: {message}'
42
+
43
+ logs.append(log+'\n')
44
+
45
+ if verbose or colorid != 39:
46
+ print(f'\033[{colorid}m'+log+'\033[0m')
47
+
48
+ class main:
49
+ def __init__(self, name : str, authorization : str):
50
+ self.authorization = authorization
51
+ self.api = 'https://api.cloudflare.com/client/v4/'
52
+ self.headers ={'Authorization' : f'Bearer {self.authorization}'}
53
+ self.zone_id = ''
54
+ self.record_id = ''
55
+ self.payload = ''
56
+ self.already_matching = []
57
+ self.name = name
58
+ self.get_ip()
59
+
60
+
61
+ def get_ip(self):
62
+ place = 'Get IP'
63
+ logger('Attempting to fetch IP',place,self.name)
64
+ response = requests.get('https://checkip.amazonaws.com/')
65
+
66
+ if response.ok:
67
+ self.ip = response.content[:-1].decode('utf-8')
68
+ logger(f'IP was succesfully fetched {self.ip}',place,self.name,32)
69
+ return(True)
70
+ logger(f'IP was not fetched status: {response.status_code}, {response.content}',place,self.name,31)
71
+ return(False)
72
+
73
+ def find_zone(self):
74
+ place = 'Zone Finder'
75
+ url = f'{self.api}/zones'
76
+ name = self.name.split('.')
77
+
78
+ logger('Fetching zones',place,self.name)
79
+
80
+ response = requests.get(url=url,headers=self.headers)
81
+
82
+ if response.ok:
83
+ zones = json.loads(response.content)
84
+
85
+ if zones['success']:
86
+ logger('Zones fetched',place,self.name,32)
87
+ for zone in zones['result']:
88
+ current_name = zone['name'].split('.')
89
+ domain_list = name[-len(current_name):]
90
+
91
+ domain = ''
92
+ for x in domain_list:
93
+ domain += '.' + x
94
+ domain = domain[1:]
95
+
96
+
97
+ if domain == zone['name']:
98
+ self.zone_id = zone['id']
99
+ logger(f'Zone found {self.zone_id}',place,self.name,32)
100
+ break
101
+ return(True)
102
+ logger('Failed to fetch zones',place,self.name,31)
103
+ return(False)
104
+
105
+ def find_record(self):
106
+ place = 'Record Finder'
107
+ url = f'{self.api}/zones/{self.zone_id}/dns_records'
108
+
109
+ logger('Fetching records',place,self.name)
110
+
111
+ response = requests.get(url=url,headers=self.headers)
112
+
113
+
114
+ if response.ok:
115
+ records = json.loads(response.content.decode('utf-8'))
116
+ if records['success']:
117
+ logger('Records fetched.',place,self.name,32)
118
+ for record in records['result']:
119
+ if record['name'] == self.name:
120
+ if record['content'] == self.ip:
121
+ self.already_matching.append(record['name'])
122
+ logger(f'Matching record found but content already matches current IP address {self.ip}',place,self.name,33)
123
+ break
124
+ else:
125
+ self.record_id = record['id']
126
+ logger(f'Matching record found {self.record_id}',place,self.name,32)
127
+ break
128
+ return(True)
129
+ logger('Failed to fetch records',place,self.name,31)
130
+ return(False)
131
+
132
+ def construct_payload(self):
133
+ place = 'Payload Constructor'
134
+ if not(self.ip):
135
+ logger('IP address not found',place,self.name,31)
136
+ self.get_ip()
137
+ return(False)
138
+ self.payload = {
139
+ 'name': self.name,
140
+ 'ttl': 1,
141
+ 'type': 'A',
142
+ 'content': self.ip,
143
+ 'proxied': False
144
+ }
145
+ return(True)
146
+
147
+ def create_record(self):
148
+ place = 'Record Creator'
149
+ url = f'{self.api}/zones/{self.zone_id}/dns_records'
150
+
151
+ headers = self.headers.copy()
152
+ headers['Content-Type'] = 'application/json'
153
+
154
+ logger(f'Creating record {self.name} with {self.ip}',place,self.name)
155
+
156
+ if self.construct_payload():
157
+ response = requests.post(url, headers=headers, json=self.payload)
158
+ return(response.ok)
159
+ return(False)
160
+
161
+ def update_record(self):
162
+ place = 'Record Updater'
163
+ url = f'{self.api}/zones/{self.zone_id}/dns_records/{self.record_id}'
164
+
165
+ headers = self.headers.copy()
166
+ headers['Content-Type'] = 'application/json'
167
+
168
+ logger(f'Updating record {self.name} with {self.ip}',place,self.name)
169
+ if self.construct_payload():
170
+ response = requests.patch(url, headers=headers, json=self.payload)
171
+ return(response.ok)
172
+ return(False)
173
+
174
+
175
+
176
+
177
+
178
+
179
+ for name in names:
180
+ place = 'Attempter'
181
+ session = main(name,authorization)
182
+ for attempt in range(1,tries+1):
183
+ logger(f'Attempt {attempt}/{tries}',place,name)
184
+ if session.find_zone() and session.zone_id:
185
+ logger(f'Zone ID {session.zone_id}',place,name)
186
+ if session.find_record() and session.record_id:
187
+ logger(f'Record ID {session.record_id}',place,name)
188
+ if session.update_record():
189
+ logger(f'Record updated with IP address {session.ip}',place,name,32)
190
+ break
191
+ elif name in session.already_matching:
192
+ logger(f'Record already matches current IP address {session.ip}, skipping.',place,name,32)
193
+ break
194
+ else:
195
+ if session.create_record():
196
+ logger(f'Record created with IP address {session.ip}',place,name,32)
197
+ break
198
+ logger(f'Attempt {attempt} Failed',place,name,31)
199
+ time.sleep(5)
200
+ except Exception as x:
201
+ logtofile = True
202
+ maxlogfiles = 5
203
+ logs.append(x)
204
+ finally:
205
+ if logtofile:
206
+ log_files = []
207
+ for file_name in os.listdir():
208
+ if file_name.startswith("cf_ddns_"):
209
+ log_files.append(file_name)
210
+ log_files.sort(reverse=True)
211
+ for log_file in log_files[maxlogfiles:]:
212
+ os.remove(log_file)
213
+
214
+ with open(f'cf_ddns_{int(time.time())}.log','w') as f:
215
+ f.writelines(logs)
216
+