This repository was archived by the owner on Nov 22, 2024. It is now read-only.
forked from cloudflare-api/python-cloudflare-v4
-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathcli4.py
More file actions
369 lines (340 loc) · 14 KB
/
cli4.py
File metadata and controls
369 lines (340 loc) · 14 KB
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#!/usr/bin/env python
"""Cloudflare API via command line"""
import sys
import re
import getopt
import json
try:
import yaml
except ImportError:
yaml = None
try:
import jsonlines
except ImportError:
jsonlines = None
from . import converters
import CloudFlare
def dump_commands():
"""dump a tree of all the known API commands"""
cf = CloudFlare.CloudFlare()
w = cf.api_list()
sys.stdout.write('\n'.join(w) + '\n')
def run_command(cf, method, command, params=None, content=None, files=None):
"""run the command line"""
# remove leading and trailing /'s
if command[0] == '/':
command = command[1:]
if command[-1] == '/':
command = command[:-1]
# break down command into it's seperate pieces
# these are then checked against the Cloudflare class
# to confirm there is a method that matches
parts = command.split('/')
cmd = []
identifier1 = None
identifier2 = None
identifier3 = None
hex_only = re.compile('^[0-9a-fA-F]+$')
waf_rules = re.compile('^[0-9]+[A-Z]*$')
m = cf
for element in parts:
if element[0] == ':':
element = element[1:]
if identifier1 is None:
if len(element) in [32, 40, 48] and hex_only.match(element):
# raw identifier - lets just use it as-is
identifier1 = element
elif element[0] == ':':
# raw string - used for workers script_name - use ::script_name
identifier1 = element[1:]
elif cmd[0] == 'certificates':
# identifier1 = convert_certificates_to_identifier(cf, element)
identifier1 = converters.convert_zones_to_identifier(cf, element)
elif cmd[0] == 'zones':
identifier1 = converters.convert_zones_to_identifier(cf, element)
elif cmd[0] == 'organizations':
identifier1 = converters.convert_organizations_to_identifier(cf, element)
elif (cmd[0] == 'user') and (cmd[1] == 'organizations'):
identifier1 = converters.convert_organizations_to_identifier(cf, element)
elif (cmd[0] == 'user') and (cmd[1] == 'invites'):
identifier1 = converters.convert_invites_to_identifier(cf, element)
elif (cmd[0] == 'user') and (cmd[1] == 'virtual_dns'):
identifier1 = converters.convert_virtual_dns_to_identifier(cf, element)
elif (cmd[0] == 'user') and (cmd[1] == 'load_balancers') and (cmd[2] == 'pools'):
identifier1 = converters.convert_load_balancers_pool_to_identifier(cf, element)
else:
exit("/%s/%s :NOT CODED YET 1" % ('/'.join(cmd), element))
cmd.append(':' + identifier1)
elif identifier2 is None:
if len(element) in [32, 40, 48] and hex_only.match(element):
# raw identifier - lets just use it as-is
identifier2 = element
elif element[0] == ':':
# raw string - used for workers script_names
identifier2 = element[1:]
elif (cmd[0] and cmd[0] == 'zones') and (cmd[2] and cmd[2] == 'dns_records'):
identifier2 = converters.convert_dns_record_to_identifier(cf,
identifier1,
element)
else:
exit("/%s/%s :NOT CODED YET 2" % ('/'.join(cmd), element))
# identifier2 may be an array - this needs to be dealt with later
if isinstance(identifier2, list):
cmd.append(':' + '[' + ','.join(identifier2) + ']')
else:
cmd.append(':' + identifier2)
identifier2 = [identifier2]
else:
if len(element) in [32, 40, 48] and hex_only.match(element):
# raw identifier - lets just use it as-is
identifier3 = element
elif waf_rules.match(element):
identifier3 = element
else:
exit("/%s/%s :NOT CODED YET 3" % ('/'.join(cmd), element))
else:
try:
m = getattr(m, element)
cmd.append(element)
except AttributeError:
# the verb/element was not found
if len(cmd) == 0:
exit('cli4: /%s - not found' % (element))
else:
exit('cli4: /%s/%s - not found' % ('/'.join(cmd), element))
if content and params:
exit('cli4: /%s - content and params not allowed together' % (command))
if content:
params = content
results = []
if identifier2 is None:
identifier2 = [None]
for i2 in identifier2:
try:
if method == 'GET':
r = m.get(identifier1=identifier1,
identifier2=i2,
identifier3=identifier3,
params=params)
elif method == 'PATCH':
r = m.patch(identifier1=identifier1,
identifier2=i2,
identifier3=identifier3,
data=params)
elif method == 'POST':
r = m.post(identifier1=identifier1,
identifier2=i2,
identifier3=identifier3,
data=params, files=files)
elif method == 'PUT':
r = m.put(identifier1=identifier1,
identifier2=i2,
identifier3=identifier3,
data=params)
elif method == 'DELETE':
r = m.delete(identifier1=identifier1,
identifier2=i2,
identifier3=identifier3,
data=params)
else:
pass
except CloudFlare.exceptions.CloudFlareAPIError as e:
if len(e) > 0:
# more than one error returned by the API
for x in e:
sys.stderr.write('cli4: /%s - %d %s\n' % (command, x, x))
exit('cli4: /%s - %d %s' % (command, e, e))
except CloudFlare.exceptions.CloudFlareInternalError as e:
exit('cli4: InternalError: /%s - %d %s' % (command, e, e))
except Exception as e:
exit('cli4: /%s - %s - api error' % (command, e))
results.append(r)
return results
def write_results(results, output):
"""dump the results"""
if len(results) == 1:
results = results[0]
if isinstance(results, str):
# if the results are a simple string, then it should be dumped directly
# this is only used for /zones/:id/dns_records/export presently
pass
else:
# anything more complex (dict, list, etc) should be dumped as JSON/YAML
if output == 'json':
try:
results = json.dumps(results,
indent=4,
sort_keys=True,
ensure_ascii=False,
encoding='utf8')
except TypeError as e:
results = json.dumps(results,
indent=4,
sort_keys=True,
ensure_ascii=False)
if output == 'yaml':
results = yaml.safe_dump(results)
if output == 'ndjson':
# NDJSON support seems like a hack. There has to be a better way
writer = jsonlines.Writer(sys.stdout)
writer.write_all(results)
writer.close()
return
sys.stdout.write(results)
if not results.endswith('\n'):
sys.stdout.write('\n')
def do_it(args):
"""Cloudflare API via command line"""
verbose = False
output = 'json'
raw = False
dump = False
method = 'GET'
usage = ('usage: cli4 '
+ '[-V|--version] [-h|--help] [-v|--verbose] [-q|--quiet] '
+ '[-j|--json] [-y|--yaml] [-n|ndjson]'
+ '[-r|--raw] '
+ '[-d|--dump] '
+ '[--get|--patch|--post|--put|--delete] '
+ '[item=value|item=@filename|@filename ...] '
+ '/command...')
try:
opts, args = getopt.getopt(args,
'VhvqjyrdGPOUD',
[
'version',
'help', 'verbose', 'quiet', 'json', 'yaml', 'ndjson',
'raw',
'dump',
'get', 'patch', 'post', 'put', 'delete'
])
except getopt.GetoptError:
exit(usage)
for opt, arg in opts:
if opt in ('-V', '--version'):
exit('Cloudflare library version: %s' % (CloudFlare.__version__))
if opt in ('-h', '--help'):
exit(usage)
elif opt in ('-v', '--verbose'):
verbose = True
elif opt in ('-q', '--quiet'):
output = None
elif opt in ('-j', '--json'):
output = 'json'
elif opt in ('-y', '--yaml'):
if yaml is None:
exit('cli4: install yaml support')
output = 'yaml'
elif opt in ('-n', '--ndjson'):
if jsonlines is None:
exit('cli4: install jsonlines support')
output = 'ndjson'
elif opt in ('-r', '--raw'):
raw = True
elif opt in ('-d', '--dump'):
dump = True
elif opt in ('-G', '--get'):
method = 'GET'
elif opt in ('-P', '--patch'):
method = 'PATCH'
elif opt in ('-O', '--post'):
method = 'POST'
elif opt in ('-U', '--put'):
method = 'PUT'
elif opt in ('-D', '--delete'):
method = 'DELETE'
if dump:
dump_commands()
exit(0)
digits_only = re.compile('^-?[0-9]+$')
floats_only = re.compile('^-?[0-9.]+$')
# next grab the params. These are in the form of tag=value or =value or @filename
params = None
content = None
files = None
while len(args) > 0 and ('=' in args[0] or args[0][0] == '@'):
arg = args.pop(0)
if arg[0] == '@':
# a file to be uploaded - used in workers/script - only via PUT
filename = arg[1:]
if method != 'PUT':
exit('cli4: %s - raw file upload only with PUT' % (filename))
try:
if filename == '-':
content = sys.stdin.read()
else:
with open(filename, 'r') as f:
content = f.read()
except IOError:
exit('cli4: %s - file open failure' % (filename))
continue
tag_string, value_string = arg.split('=', 1)
if value_string.lower() == 'true':
value = True
elif value_string.lower() == 'false':
value = False
elif value_string == '' or value_string.lower() == 'none':
value = None
elif value_string[0] == '=' and value_string[1:] == '':
exit('cli4: %s== - no number value passed' % (tag_string))
elif value_string[0] == '=' and digits_only.match(value_string[1:]):
value = int(value_string[1:])
elif value_string[0] == '=' and floats_only.match(value_string[1:]):
value = float(value_string[1:])
elif value_string[0] == '=':
exit('cli4: %s== - invalid number value passed' % (tag_string))
elif value_string[0] in '[{' and value_string[-1] in '}]':
# a json structure - used in pagerules
try:
#value = json.loads(value) - changed to yaml code to remove unicode string issues
if yaml is None:
exit('cli4: install yaml support')
value = yaml.safe_load(value_string)
except ValueError:
exit('cli4: %s="%s" - can\'t parse json value' % (tag_string, value_string))
elif value_string[0] == '@':
# a file to be uploaded - used in dns_records/import - only via POST
filename = value_string[1:]
if method != 'POST':
exit('cli4: %s=%s - file upload only with POST' % (tag_string, filename))
files = {}
try:
if filename == '-':
files[tag_string] = sys.stdin
else:
files[tag_string] = open(filename, 'rb')
except IOError:
exit('cli4: %s=%s - file open failure' % (tag_string, filename))
# no need for param code below
continue
else:
value = value_string
if tag_string == '':
# There's no tag; it's just an unnamed list
if params is None:
params = []
try:
params.append(value)
except AttributeError:
exit('cli4: %s=%s - param error. Can\'t mix unnamed and named list' %
(tag_string, value_string))
else:
if params is None:
params = {}
tag = tag_string
try:
params[tag] = value
except TypeError:
exit('cli4: %s=%s - param error. Can\'t mix unnamed and named list' %
(tag_string, value_string))
# what's left is the command itself
if len(args) != 1:
exit(usage)
command = args[0]
cf = CloudFlare.CloudFlare(debug=verbose, raw=raw)
results = run_command(cf, method, command, params, content, files)
write_results(results, output)
def cli4(args):
"""Cloudflare API via command line"""
do_it(args)
exit(0)