-
Notifications
You must be signed in to change notification settings - Fork 7
/
net.py
657 lines (602 loc) · 24.8 KB
/
net.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
#! /usr/bin/env python
"""
This script is the main engine to make backend calls to network
devices and present the data back in a structured format to the
web front end.
"""
# Import modules
import os
from os import environ
from flask import jsonify
from nornir import InitNornir
from nornir_netmiko.tasks import netmiko_send_command
from nornir_napalm.plugins.tasks import napalm_cli, napalm_get
from nornir_scrapli.tasks import send_command
from colorama import Fore, init
# Auto-reset colorama colours back after each print statement
init(autoreset=True)
# Gathering environmental variables and assigning to variables to use throughout code.
# Check whether NET_TESTFSM variable has been set, not mandatory, but recommeneded
if environ.get("NET_TEXTFSM") is None:
# Print warning
print(
Fore.YELLOW
+ str("*" * 15)
+ " WARNING: Environmental variable `NET_TEXTFSM` not set. "
+ "*" * 15
)
# Check whether NORNIR_DEFAULT_USERNAME variable has been set, not mandatory, but recommeneded
if environ.get("NORNIR_DEFAULT_USERNAME") is not None:
# Set the env_uname to this variable so it can be used for the Nornir inventory
env_uname = os.environ["NORNIR_DEFAULT_USERNAME"]
else:
# Print warning
print(
Fore.YELLOW
+ "*" * 15
+ " WARNING: Environmental variable `NORNIR_DEFAULT_USERNAME` not set. "
+ "*" * 15
)
# Set the env_uname to an empty string, so that the code does not error out.
# NOTE: It's valid form to use the groups.yaml and hosts.yaml file(s) to
# store credentials so this will not raise an exception
env_uname = ""
# Print supplementary warning
print(
Fore.MAGENTA
+ "*" * 15
+ " NOTIFICATION: Environmental variable `NORNIR_DEFAULT_USERNAME` now set to ''."
+ "This may cause all authentication to fail. "
+ "*" * 15
)
# Check whether NORNIR_DEFAULT_PASSWORD variable has been set, not mandatory, but recommeneded
if environ.get("NORNIR_DEFAULT_PASSWORD") is not None:
# Set the env_pword to this variable so it can be used for the Nornir inventory
env_pword = os.environ["NORNIR_DEFAULT_PASSWORD"]
else:
print(
Fore.YELLOW
+ "*" * 15
+ " WARNING: Environmental variable `NORNIR_DEFAULT_PASSWORD` not set. "
+ "*" * 15
)
# Set the env_pword to an empty string, so that the code does not error out.
# NOTE: It's valid form to use the groups.yaml and hosts.yaml file(s) to
# store credentials so this will not raise an exception
env_pword = ""
print(
Fore.MAGENTA
+ "*" * 15
+ " NOTIFICATION: Environmental variable `NORNIR_DEFAULT_PASSWORD` now set to ''."
+ "This may cause all authentication to fail. "
+ "*" * 15
)
# General functions, consumed by other functions
def get_nr():
"""
Initialises a Nornir inventory from the various configuration
files
:return nr: An initialised Nornir inventory for use in other functions.
"""
nr = InitNornir(
inventory={
"options": {
"host_file": "inventory/hosts.yaml",
"group_file": "inventory/groups.yaml",
"defaults_file": "inventory/defaults.yaml",
}
}
)
# Set default username and password from environmental variables.
nr.inventory.defaults.username = env_uname
nr.inventory.defaults.password = env_pword
return nr
def to_json(results):
"""
Takes some Nornir results and runs them through jsonify to produce a structured result.
:param results: The results to be processed
:return j_results: Results after they have been run through jsonify
"""
j_results = jsonify({host: result[0].result for host, result in results.items()})
return j_results
# Inventory functions
def get_inv_all():
"""
Retrieves the entire Nornir inventory into a dictionary and prepares
it to preparation for consumption by the front end.
NOTE: The default username and password are replaced with `**REDACTED**`
so that these credentials are not exposed to the front-end.
:return jsonify(r): Results after they have been run through jsonify
"""
# Initialise Nornir
nr = get_nr()
# Overwrite the default username and password,
# so that users cannot exploit it
nr.inventory.defaults.username = "**REDACTED**"
nr.inventory.defaults.password = "**REDACTED**"
# This calls all results of the get inventory dictionary call.
r = nr.inventory.dict()
return jsonify(r)
def get_inv_hosts():
"""
Retrieves the Nornir hosts inventory into a dictionary and prepares
it to preparation for consumption by the front end.
:return jsonify(r): Results after they have been run through jsonify
"""
# Initialise Nornir
nr = get_nr()
# This calls all results of the get inventory dictionary call.
# This is not ideal
r_all = nr.inventory.dict()
# Access the host directory results
r = r_all["hosts"]
return jsonify(r)
def get_inv_groups():
"""
Retrieves the Nornir groups inventory into a dictionary and prepares
it to preparation for consumption by the front end.
:return jsonify(r): Results after they have been run through jsonify
"""
# Initialise Nornir
nr = get_nr()
# This calls all results of the get inventory dictionary call.
# This is not ideal
r_all = nr.inventory.dict()
# Access the groups directory results
r = r_all["groups"]
return jsonify(r)
# NAPALM getter functions
def get_users_all():
"""
Retrieves the results of `get_users` for all hosts in the Nornir
inventory and prepares it for consumption by
the front end.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Execute napalm get_users task
r = nr.run(task=napalm_get, getters=["users"])
# If/Else block to validate whether the task failed or not
# If the task fails
print("*" * 20)
print(r.failed)
if r.failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r.failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def get_facts_all():
"""
Retrieves the results of `get_facts` for all hosts in the Nornir
inventory and prepares it for consumption by
the front end.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Execute napalm get_facts task
r = nr.run(task=napalm_get, getters=["facts"])
# If/Else block to validate whether the task failed or not
# If the task fails
if r.failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r.failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def get_interfaces_all():
"""
Retrieves the results of `get_interfaces` for all hosts in the Nornir
inventory and prepares it for consumption by
the front end.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Execute napalm get_interfaces task
r = nr.run(task=napalm_get, getters=["interfaces"])
# If/Else block to validate whether the task failed or not
# If the task fails
if r.failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r.failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def get_interfaces_ip_all():
"""
Retrieves the results of `get_interfaces_ip` for all hosts in the Nornir
inventory and prepares it for consumption by
the front end.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Execute napalm get_interfaces_ip task
r = nr.run(task=napalm_get, getters=["interfaces_ip"])
# If/Else block to validate whether the task failed or not
# If the task fails
if r.failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r.failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def get_ntp_servers_all():
"""
Retrieves the results of `get_ntp_servers` for all hosts in the Nornir
inventory and prepares it for consumption by
the front end.
:return to_json(r): Results after they have been run through jsonify
"""
# Initialise Nornir
nr = get_nr()
# Execute napalm get_ntp_servers task
r = nr.run(task=napalm_get, getters=["ntp_servers"])
# If/Else block to validate whether the task failed or not
# If the task fails
if r.failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r.failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def get_facts_host(host):
"""
Retrieves the results of `get_facts` for an individual host
of the Nornir inventory and prepares it to preparation for
consumption by the front end.
:param host: The host which is to be queried.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
r = device.run(name="Processing facts", task=napalm_get, getters=["facts"])
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r[host].failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def get_users_host(host):
"""
Retrieves the results of `get_users` for an individual host
of the Nornir inventory and prepares it to preparation for
consumption by the front end.
:param host: The host which is to be queried.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
# Execute napalm get_users task
r = device.run(name="Processing users", task=napalm_get, getters=["users"])
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r[host].failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def get_interfaces_host(host):
"""
Retrieves the results of `get_interfaces` for an individual host
of the Nornir inventory and prepares it to preparation for
consumption by the front end.
:param host: The host which is to be queried.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
# Execute napalm get_interfaces task
r = device.run(
name="Processing interfaces", task=napalm_get, getters=["interfaces"]
)
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r[host].failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def get_interfaces_ip_host(host):
"""
Retrieves the results of `get_interfaces_ip` for an individual host
of the Nornir inventory and prepares it to preparation for
consumption by the front end.
:param host: The host which is to be queried.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
# Execute napalm get_interfaces_ip task
r = device.run(
name="Processing IP interfaces", task=napalm_get, getters=["interfaces_ip"]
)
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r[host].failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def get_ntp_servers_host(host):
"""
Retrieves the results of `get_ntp_servers` for an individual host
of the Nornir inventory and prepares it to preparation for
consumption by the front end.
:param host: The host which is to be queried.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
# Execute napalm get_ntp_servers task
r = device.run(
name="Processing NTP Servers", task=napalm_get, getters=["ntp_servers"]
)
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r[host].failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def get_getter_host(host, getter):
"""
Retrieves the results of a supplied getter for an individual host
of the Nornir inventory and prepares it to preparation for
consumption by the front end.
:param host: The host which is to be queried.
:param getter: The getter to be retrieved.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
# Execute napalm get_interfaces task
r = device.run(name="Processing IP interfaces", task=napalm_get, getters=[getter])
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r[host].failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def napalm_cli_host(host, command):
"""
Retrieves the results of an individual command for an individual host
of the Nornir inventory using the `napalm_cli` function
and prepares it to preparation for
consumption by the front end.
:param host: The host which is to be queried.
:param command: The command to be run on the host.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
# Execute napalm_cli command
r = device.run(name="NAPALM CLI", task=napalm_cli, commands=[command])
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r[host].failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def netmiko_genie_host(host, command):
"""
Retrieves the results of an individual command for an individual host
of the Nornir inventory using the `use_genie=True` through the
`netmiko_send_command` and prepares it to preparation for
consumption by the front end.
:param host: The host which is to be queried.
:param command: The command to be run on the host.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
# Execute netmiko send command, using Genie
r = device.run(
task=netmiko_send_command,
name="Netmiko Command (Genie)",
command_string=command,
use_textfsm=False,
use_genie=True,
)
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r[host].failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def netmiko_textfsm_host(host, command):
"""
Retrieves the results of an individual command for an individual host
of the Nornir inventory using the `use_textfsm=True` through the
`netmiko_send_command` and prepares it to preparation for
consumption by the front end.
:param host: The host which is to be queried.
:param command: The command to be run on the host.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
# Execute netmiko send command, using Genie
r = device.run(
task=netmiko_send_command,
name="Netmiko Command (TextFSM)",
command_string=command,
use_textfsm=True,
)
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r[host].failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def netmiko_host(host, command):
"""
Retrieves the results of an individual command for an individual host
of the Nornir inventory using the
`netmiko_send_command` and prepares it to preparation for
consumption by the front end.
:param host: The host which is to be queried.
:param command: The command to be run on the host.
:return to_json(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
# Execute netmiko send command, using Genie
r = device.run(
task=netmiko_send_command,
name="Netmiko Command",
command_string=command,
)
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r[host].failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200
def scrapli_genie_host(host, command):
"""
Retrieves the results of an individual command for an individual host
of the Nornir inventory using Scrapli `send_command`, parsed through the
genie parser and prepares it for consumption by the front end.
:param host: The host which is to be queried.
:param command: The command to be run on the host.
:return jsonify(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
# Execute scrapli send command
r = device.run(task=send_command, name="Scrapli Send Command", command=command)
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return jsonify(host=host, command_output=""), 500
# If the task succeeds
elif r[host].failed is False:
# Use genie_parse_output to parse Nornir AggregatedResult via Genie
output = r[host].scrapli_response.genie_parse_output()
# Jsonify the host and the output, send the response and status code 200
return jsonify(host=host, command_output=output), 200
def scrapli_textfsm_host(host, command):
"""
Retrieves the results of an individual command for an individual host
of the Nornir inventory using Scrapli `send_command`, parsed through the
TextFSM parser and prepares it for consumption by the front end.
:param host: The host which is to be queried.
:param command: The command to be run on the host.
:return jsonify(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
# Execute scrapli send command
r = device.run(task=send_command, name="Scrapli Send Command", command=command)
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return jsonify(host=host, command_output=""), 500
# If the task succeeds
elif r[host].failed is False:
# Use genie_parse_output to parse Nornir AggregatedResult via TextFSM
output = r[host].scrapli_response.textfsm_parse_output()
# Jsonify the host and the output, send the response and status code 200
return jsonify(host=host, command_output=output), 200
def scrapli_host(host, command):
"""
Retrieves the results of an individual command for an individual host
of the Nornir inventory using Scrapli `send_command` and prepares
it for consumption by the front end.
:param host: The host which is to be queried.
:param command: The command to be run on the host.
:return jsonify(r), status_code: Results after they have been run through
jsonify and respective status code
"""
# Initialise Nornir
nr = get_nr()
# Filter by the host supplied into the function
device = nr.filter(name=str(host))
# Execute scrapli send command
r = device.run(task=send_command, name="Scrapli Send Command", command=command)
# If/Else block to validate whether the task failed or not
# If the task fails
if r[host].failed is True:
# Jsonify the host and the output, send the response and status code 500
return to_json(r), 500
# If the task succeeds
elif r[host].failed is False:
# Jsonify the host and the output, send the response and status code 200
return to_json(r), 200