forked from xens/ripeinator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathripe.py
executable file
·354 lines (302 loc) · 10.3 KB
/
ripe.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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import json
import os
from pprint import pprint
import requests
import sys
import yaml
def ripe_create(db, pwd, json_output, key, type, dryrun, object_entries):
"""
Create non-existing RIPE object
"""
if type == "route" or type == "route6":
for i in object_entries:
if list(i.keys())[0] == "origin":
key = f"{key}{i['origin']}"
# parameters for create request
params = dict()
params["password"] = pwd
params["dry-run"] = dryrun
url = f"{db}/ripe/{type}"
headers = {
"Content-Type": "application/json",
"Accept": "application/json; charset=utf-8",
}
r = requests.post(url, data=json_output, headers=headers)
# print (r.text)
eval_write_answer(r.status_code, r.text, dryrun)
def ripe_get(db, type, object, object_entries):
"""
Get RIPE objects from the RIPE database
"""
if type == "route" or type == "route6":
for i in object_entries:
if list(i.keys())[0] == "origin":
object = f"{object}{i['origin']}"
url = f"{db}/ripe/{type}/{object}?unfiltered"
headers = {"Accept": "application/json"}
r = requests.get(url, headers=headers)
output = json.loads(r.text)
return output
def ripe_update(db, pwd, json_output, key, type, dryrun, object_entries):
"""
Update exsting RIPE object on the RIPE database
"""
if type == "route" or type == "route6":
for i in object_entries:
if list(i.keys())[0] == "origin":
key = f"{key}{i['origin']}"
# parameters for update request
params = dict()
params["password"] = pwd
params["dry-run"] = dryrun
url = f"{db}/ripe/{type}/{key}"
headers = {
"Content-Type": "application/json",
"Accept": "application/json; charset=utf-8",
}
r = requests.put(url, data=json_output, params=params, headers=headers)
eval_write_answer(r.status_code, r.text, dryrun)
def ripe_search(db, attribute, string):
"""
Search object in the RIPE database
"""
# common parameters - used for forward and reverse search
params = dict()
params["source"] = "ripe"
params["query-string"] = string
params["flags"] = ("no-filtering", "no-referenced")
# if attribute given add to params dict - trigger inverse search
if attribute:
params["inverse-attribute"] = attribute
url = f"{db}/search"
headers = {"Accept": "application/json"}
r = requests.get(url, params=params, headers=headers)
output = json.loads(r.text)
return output
def object_comparator_lookup(src_obj, dst_obj):
"""
Compare an object with another entry by entry
"""
dont_match = []
no_upstream = []
for i in dst_obj:
count_name = 0
count_value = 0
for j in src_obj:
if list(j.keys())[0] == list(i.keys())[0]:
count_name = 1
if j[list(j.keys())[0]] == i[list(i.keys())[0]]:
count_value = 1
if count_name == 0:
if list(i.keys())[0] != "last-modified":
print(i.keys(), list(i.keys())[0])
no_upstream.append(i)
else:
if count_value == 0:
dont_match.append(i)
if no_upstream or dont_match:
return 1
else:
return 0
def object_comparator_strict(src_obj, dst_obj):
"""
Compare an object with another entry by entry
"""
for i in range(len(dst_obj)):
if list(dst_obj[i].keys())[0] == "last-modified":
del dst_obj[i]
break
dont_match = []
failed_keys = 0
failed_values = 0
count = 0
if len(src_obj) == len(dst_obj):
for i in src_obj:
if list(i.keys())[0] == list(dst_obj[count].keys())[0]:
if (
i[list(i.keys())[0]]
!= dst_obj[count][list(dst_obj[count].keys())[0]]
):
failed_values += 1
else:
failed_keys += 1
count += 1
if failed_keys or failed_values:
return 1
else:
return 0
else:
return 1
def yaml_parser(objects):
"""
TODO
"""
a = open(objects, "r")
objects = yaml.full_load(a.read())
return objects
def eval_search(ripe_object, name, value):
"""
Evaluate RIPE answer when searching objects
"""
# print(ripe_object)
try:
error = ripe_object["errormessages"]["errormessage"][0]["text"]
if error.find("101"):
return 1
else:
return 2
except:
return 0
def eval_write_answer(status_code, text, dryrun):
"""
Evaluate RIPE answer when writing objects
"""
if dryrun:
try:
exists = json.loads(text)["errormessages"]["errormessage"][0]["text"]
except:
print(f" RIPE answer: {text}")
else:
info = json.loads(text)["errormessages"]["errormessage"]
for item in info:
print(item["text"])
if "args" in item:
print(item["args"][0]["value"])
else:
if status_code == 200:
print(" RIPE answer: upstream object written")
else:
output = json.loads(text)["errormessages"]["errormessage"][0]["text"]
print(f" RIPE answer: {output}")
def yaml_to_json(yml_object):
"""
Re-create RIPE json format from yaml
"""
construct = {
"objects": {
"object": [{"source": {"id": "RIPE"}, "attributes": {"attribute": []}}]
}
}
for i in yml_object:
construct["objects"]["object"][0]["attributes"]["attribute"].append(
{"name": list(i.keys())[0], "value": i[list(i.keys())[0]]}
)
return json.dumps(construct)
def json_to_yaml(json_payload):
"""
Convert json to yaml
"""
objects = {}
for i in json_payload["objects"]["object"]:
objects[i["primary-key"]["attribute"][0]["value"]] = []
for j in i["attributes"]["attribute"]:
if j["name"] != "last-modified":
objects[i["primary-key"]["attribute"][0]["value"]].append(
{j["name"]: j["value"]}
)
yaml_out = yaml.dump(yaml.full_load(json.dumps(objects)), default_flow_style=False)
return yaml_out
def ripe_normalize(ripe_obj):
new_obj = []
for i in ripe_obj:
new_obj.append({i["name"]: i["value"]})
return new_obj
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--db", required=False, help="Database URL", default="https://rest.db.ripe.net"
)
group = parser.add_mutually_exclusive_group()
group.add_argument("--objects", required=False, help="Objects to compare / write")
group.add_argument(
"--search", required=False, help="Search for a particular string"
)
parser.add_argument(
"--dryrun",
required=False,
action="store_true",
help="Perform validation and not the upgrade",
)
parser.add_argument(
"--pwd", required=False, help="Password needed to write objects"
)
parser.add_argument(
"--attribute", required=False, help="Search for a specific attribute"
)
args = parser.parse_args()
# if cmdline arguments for objects are given
if args.objects:
# check for password
## if not given via cmdline try env var -> exit on error
if not args.pwd:
try:
pwd = os.environ["RIPE_PASSWORD"]
except:
print(f"no RIPE_PASSWORD environment variable found")
print()
parser.print_usage()
if not args.dryrun:
sys.exit(1)
else:
pwd = args.pwd
yml_objects = yaml_parser(args.objects)
for key in yml_objects.keys():
type = list(yml_objects[key][0].keys())[0]
name = key
print("")
print(type, key)
ripe_object = ripe_get(args.db, type, name, yml_objects[key])
answer = eval_search(ripe_object, type, name)
if answer == 0:
ripe_object = ripe_object["objects"]["object"][0]["attributes"][
"attribute"
]
ripe_obj = ripe_normalize(ripe_object)
ripe_comparison = object_comparator_lookup(ripe_obj, yml_objects[key])
local_comparison = object_comparator_lookup(yml_objects[key], ripe_obj)
strict_comparison = object_comparator_strict(yml_objects[key], ripe_obj)
if (
strict_comparison == 0
and ripe_comparison == 0
and local_comparison == 0
):
print(f" Entries are consistent")
else:
print(f" Entries are not consistent")
pprint(yml_objects[key])
json_output = yaml_to_json(yml_objects[key])
ripe_update(
args.db,
pwd,
json_output,
key,
type,
args.dryrun,
yml_objects[key],
)
if answer == 1:
print(f"Object does not exists in the RIPE database")
json_output = yaml_to_json(yml_objects[key])
ripe_create(
args.db, pwd, json_output, key, type, args.dryrun, yml_objects[key]
)
# else if cmdline argument for search is given
elif args.search:
# inverse search for specific objects with specific attributes
if args.attribute:
search_results = ripe_search(args.db, args.attribute, args.search)
answer = eval_search(search_results, args.attribute, args.search)
# forward search for some object
else:
search_results = ripe_search(args.db, None, args.search)
answer = eval_search(search_results, None, args.search)
if answer == 0:
print(json_to_yaml(search_results))
else:
sys.exit(1)
# if neither search nor objects are given -> print usage
else:
parser.print_usage()