-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloudflare_proxy.py
200 lines (164 loc) · 6.54 KB
/
cloudflare_proxy.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
from __future__ import absolute_import
from __future__ import print_function
import re
import CloudFlare
import yaml
import datetime
import time
import glob
import os
import argparse
# Global Variables
max_requests = 800
api_sleep_time_in_seconds = 320
def connect():
cf = CloudFlare.CloudFlare(raw=True)
return cf
def get_zone_info(cf):
response = cf.zones.get(params={'per_page': 50})
total_pages = response['result_info']['total_pages']
page = 0
zones = []
zone_info_dict = {}
while page <= total_pages:
page += 1
response = cf.zones.get(params={'page': page, 'per_page': 50})
zones.extend(response['result'])
for zone in zones:
zone_info_dict[zone['name']] = zone['id']
return zone_info_dict
def read_yaml_backup_file():
file_list = []
zone_record_dict = {}
os.chdir("/tmp")
for file in glob.glob("cloudflare-backup-dns-*.yml"):
file_list.append(file)
for file in file_list:
txt_filename = file
re1 = '.*?' # Non-greedy match on filler
# File Name 1
re2 = '((?:[a-z][a-z\\.\\d_]+)\\.(?:[a-z\\d]{3}))(?![\\w\\.])'
rg = re.compile(re1 + re2, re.IGNORECASE | re.DOTALL)
m = rg.search(txt_filename)
if m:
file1 = m.group(1)
domain = file1.split('.yml')
zone_record_dict[domain[0]] = yaml_load_all(txt_filename)
print('Finished reading: ' + txt_filename)
return zone_record_dict
def yaml_load_all(filename):
with open(filename, 'r') as ymlfile:
return yaml.load(ymlfile)
def set_proxy(cf, zone_record_dict, set_flag):
zone_info_dict = get_zone_info(cf)
total_records = sum([len(value)
for key, value in zone_record_dict.iteritems()])
print('Total records: ' + str(total_records))
count = 0
for domain_zone in zone_record_dict:
for single_domain in zone_record_dict[domain_zone]:
count += 1
start_time = datetime.datetime.now()
for fqdn, record_values in single_domain.iteritems():
print(count)
current_time = datetime.datetime.now()
duration = (current_time - start_time)
if count >= max_requests or duration.seconds >= 240:
countdown_time(api_sleep_time_in_seconds)
count = 0 # reset count
start_time = datetime.datetime.now() # reset start_time
print('counter/start_time reset')
else:
if set_flag == True:
# Disable proxy ONLY for records which have proxy Enabled currently - if records have proxy
# enabled already skip them (as per backup
# configuration being read
if record_values['proxiable'] and record_values[
'proxied'] == True:
print('Disabling Proxy for: ' +
fqdn +
' current value: ' +
str(record_values['proxied']))
disable_proxy(
cf, zone_info_dict[domain_zone], fqdn, record_values)
else:
print(
'Cannot set Proxy for: ' +
fqdn +
' not proxiable! or already disabled')
elif set_flag == False:
# Disable proxy ONLY for records who's backup
# configuration states it should be disabled
if record_values['proxiable']:
print('Reseting Proxy for: ' +
fqdn +
' to original value: ' +
str(record_values['proxied']))
reset_proxy(
cf, zone_info_dict[domain_zone], fqdn, record_values)
else:
print(
'Cannot set Proxy for: ' +
fqdn +
' not proxiable!')
def countdown_time(time_in_seconds):
# print('Waiting for few minutes so that we don\'t hit the API Rate Limit \n')
while time_in_seconds:
mins, secs = divmod(time_in_seconds, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat)
time.sleep(1)
time_in_seconds -= 1
print('Finished waiting for API limit cooldown timer!\n\n\n\n\n')
def disable_proxy(cf, zone_id, fqdn, record_values):
dns_record = {
'zone_id': zone_id,
'id': record_values['id'],
'proxied': False,
'type': record_values['type'],
'name': fqdn,
'content': record_values['content'],
'ttl': record_values['ttl']
}
response = cf.zones.dns_records.put(
zone_id, record_values['id'], data=dns_record)
return response
def reset_proxy(cf, zone_id, fqdn, record_values):
dns_record = {
'zone_id': zone_id,
'id': record_values['id'],
'proxied': record_values['proxied'],
'type': record_values['type'],
'name': fqdn,
'content': record_values['content'],
'ttl': record_values['ttl']
}
response = cf.zones.dns_records.put(
zone_id, record_values['id'], data=dns_record)
return response
def cli_args():
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--disable', action='store_true', default=None,
help='Sets Cloudflare Proxy to OFF/Diable for ALL records')
group.add_argument('--restore', action='store_false', default=None,
help='Restores Cloudflare proxy settings to those in the backup file')
parser.parse_args()
args = parser.parse_args()
print(args)
if args.disable or args.restore != None:
cf = connect()
zone_record_dict = read_yaml_backup_file()
if args.disable == True:
print('Disabing Proxy')
set_proxy(cf, zone_record_dict, args.disable)
elif args.restore == False:
print('Restoring Proxy settings')
set_proxy(cf, zone_record_dict, args.restore)
else:
print(parser.print_help())
def main():
cli_args()
print('Finished processing all records!!!')
if __name__ == '__main__':
main()