/
nxos.py
1113 lines (983 loc) · 44.1 KB
/
nxos.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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright 2015 Spotify AB. All rights reserved.
#
# The contents of this file are licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
from __future__ import unicode_literals
# import stdlib
import re
import time
import tempfile
from datetime import datetime
from requests.exceptions import ConnectionError
# import third party lib
from netaddr import IPAddress
from netaddr.core import AddrFormatError
from pynxos.device import Device as NXOSDevice
from pynxos.features.file_copy import FileTransferError as NXOSFileTransferError
from pynxos.features.file_copy import FileCopy
from pynxos.errors import CLIError
# import NAPALM Base
import napalm.base.helpers
from napalm.base import NetworkDriver
from napalm.base.utils import py23_compat
from napalm.base.exceptions import ConnectionException
from napalm.base.exceptions import MergeConfigException
from napalm.base.exceptions import CommandErrorException
from napalm.base.exceptions import ReplaceConfigException
import napalm.base.constants as c
class NXOSDriverBase(NetworkDriver):
"""Common code shared between nx-api and nxos_ssh."""
def commit_config(self, message=""):
if message:
raise NotImplementedError('Commit message not implemented for this platform')
if self.loaded:
# Create checkpoint from current running-config
self.backup_file = 'config_' + str(datetime.now()).replace(' ', '_')
self._save_to_checkpoint(self.backup_file)
if self.replace:
# Replace operation
self._load_cfg_from_checkpoint()
else:
# Merge operation
self._commit_merge()
self._copy_run_start()
self.changed = True
self.loaded = False
else:
raise ReplaceConfigException('No config loaded.')
def ping(self,
destination,
source=c.PING_SOURCE,
ttl=c.PING_TTL,
timeout=c.PING_TIMEOUT,
size=c.PING_SIZE,
count=c.PING_COUNT,
vrf=c.PING_VRF):
"""
Execute ping on the device and returns a dictionary with the result.
Output dictionary has one of following keys:
* success
* error
In case of success, inner dictionary will have the followin keys:
* probes_sent (int)
* packet_loss (int)
* rtt_min (float)
* rtt_max (float)
* rtt_avg (float)
* rtt_stddev (float)
* results (list)
'results' is a list of dictionaries with the following keys:
* ip_address (str)
* rtt (float)
"""
ping_dict = {}
version = ''
try:
version = '6' if IPAddress(destination).version == 6 else ''
except AddrFormatError:
# Allow use of DNS names
pass
command = 'ping{version} {destination}'.format(
version=version,
destination=destination)
command += ' timeout {}'.format(timeout)
command += ' packet-size {}'.format(size)
command += ' count {}'.format(count)
if source != '':
command += ' source {}'.format(source)
if vrf != '':
command += ' vrf {}'.format(vrf)
output = self._send_command(command)
if 'connect:' in output:
ping_dict['error'] = output
elif 'PING' in output:
ping_dict['success'] = {
'probes_sent': 0,
'packet_loss': 0,
'rtt_min': 0.0,
'rtt_max': 0.0,
'rtt_avg': 0.0,
'rtt_stddev': 0.0,
'results': []
}
results_array = []
for line in output.splitlines():
fields = line.split()
if 'icmp' in line:
if 'Unreachable' in line:
if "(" in fields[2]:
results_array.append(
{
'ip_address': py23_compat.text_type(fields[2][1:-1]),
'rtt': 0.0,
}
)
else:
results_array.append({'ip_address': py23_compat.text_type(fields[1]),
'rtt': 0.0})
elif 'truncated' in line:
if "(" in fields[4]:
results_array.append(
{
'ip_address': py23_compat.text_type(fields[4][1:-2]),
'rtt': 0.0,
}
)
else:
results_array.append(
{
'ip_address': py23_compat.text_type(fields[3][:-1]),
'rtt': 0.0,
}
)
elif fields[1] == 'bytes':
if version == '6':
m = fields[5][5:]
else:
m = fields[6][5:]
results_array.append({'ip_address': py23_compat.text_type(fields[3][:-1]),
'rtt': float(m)})
elif 'packets transmitted' in line:
ping_dict['success']['probes_sent'] = int(fields[0])
ping_dict['success']['packet_loss'] = int(fields[0]) - int(fields[3])
elif 'min/avg/max' in line:
m = fields[3].split('/')
ping_dict['success'].update({
'rtt_min': float(m[0]),
'rtt_avg': float(m[1]),
'rtt_max': float(m[2]),
})
ping_dict['success'].update({'results': results_array})
return ping_dict
class NXOSDriver(NXOSDriverBase):
def __init__(self, hostname, username, password, timeout=60, optional_args=None):
if optional_args is None:
optional_args = {}
self.hostname = hostname
self.username = username
self.password = password
self.timeout = timeout
self.up = False
self.replace = True
self.loaded = False
self.fc = None
self.changed = False
self.replace_file = None
self.merge_candidate = ''
# nxos_protocol is there for backwards compatibility, transport is the preferred method
self.transport = optional_args.get('transport', optional_args.get('nxos_protocol', 'https'))
if self.transport == 'https':
self.port = optional_args.get('port', 443)
elif self.transport == 'http':
self.port = optional_args.get('port', 80)
def open(self):
try:
self.device = NXOSDevice(self.hostname,
self.username,
self.password,
timeout=self.timeout,
port=self.port,
transport=self.transport)
self.device.show('show hostname')
self.up = True
except (CLIError, ValueError):
# unable to open connection
raise ConnectionException('Cannot connect to {}'.format(self.hostname))
def close(self):
if self.changed:
self._delete_file(self.backup_file)
self.device = None
def _send_command(self, command):
"""Wrapper for CLI method in NX-API.
Allows more code sharing between NX-API and SSH.
"""
return self.cli([command]).get(command)
@staticmethod
def _compute_timestamp(stupid_cisco_output):
"""
Some fields such `uptime` are returned as: 23week(s) 3day(s)
This method will determine the epoch of the event.
e.g.: 23week(s) 3day(s) -> 1462248287
"""
if not stupid_cisco_output or stupid_cisco_output == 'never':
return -1.0
if '(s)' in stupid_cisco_output:
pass
elif ':' in stupid_cisco_output:
stupid_cisco_output = stupid_cisco_output.replace(':', 'hour(s) ', 1)
stupid_cisco_output = stupid_cisco_output.replace(':', 'minute(s) ', 1)
stupid_cisco_output += 'second(s)'
else:
stupid_cisco_output = stupid_cisco_output.replace('d', 'day(s) ')
stupid_cisco_output = stupid_cisco_output.replace('h', 'hour(s)')
things = {
'second(s)': {
'weight': 1
},
'minute(s)': {
'weight': 60
},
'hour(s)': {
'weight': 3600
},
'day(s)': {
'weight': 24 * 3600
},
'week(s)': {
'weight': 7 * 24 * 3600
},
'year(s)': {
'weight': 365.25 * 24 * 3600
}
}
things_keys = things.keys()
for part in stupid_cisco_output.split():
for key in things_keys:
if key in part:
things[key]['count'] = napalm.base.helpers.convert(
int, part.replace(key, ''), 0)
delta = sum([det.get('count', 0) * det.get('weight') for det in things.values()])
return time.time() - delta
@staticmethod
def _get_reply_body(result):
# useful for debugging
ret = result.get('ins_api', {}).get('outputs', {}).get('output', {}).get('body', {})
# Original 'body' entry may have been an empty string, don't return that.
if not isinstance(ret, dict):
return {}
return ret
@staticmethod
def _get_table_rows(parent_table, table_name, row_name):
# because if an inconsistent piece of shit.
# {'TABLE_intf': [{'ROW_intf': {
# vs
# {'TABLE_mac_address': {'ROW_mac_address': [{
# vs
# {'TABLE_vrf': {'ROW_vrf': {'TABLE_adj': {'ROW_adj': {
_table = parent_table.get(table_name)
_table_rows = []
if isinstance(_table, list):
_table_rows = [_table_row.get(row_name) for _table_row in _table]
elif isinstance(_table, dict):
_table_rows = _table.get(row_name)
if not isinstance(_table_rows, list):
_table_rows = [_table_rows]
return _table_rows
@staticmethod
def fix_checkpoint_string(string, filename):
# used to generate checkpoint-like files
pattern = '''!Command: Checkpoint cmd vdc 1'''
if '!Command' in string:
return re.sub('!Command.*', pattern.format(filename), string)
else:
return "{0}\n{1}".format(pattern.format(filename), string)
def _get_reply_table(self, result, table_name, row_name):
return self._get_table_rows(result, table_name, row_name)
def _get_command_table(self, command, table_name, row_name):
json_output = self.device.show(command)
return self._get_reply_table(json_output, table_name, row_name)
def is_alive(self):
if self.device:
return {'is_alive': True}
else:
return {'is_alive': False}
def load_replace_candidate(self, filename=None, config=None):
self.replace = True
self.loaded = True
if not filename and not config:
raise ReplaceConfigException('filename or config param must be provided.')
if filename is None:
temp_file = tempfile.NamedTemporaryFile()
temp_file.write(config)
temp_file.flush()
cfg_filename = temp_file.name
else:
cfg_filename = filename
self.replace_file = cfg_filename
with open(self.replace_file, 'r') as f:
file_content = f.read()
file_content = self.fix_checkpoint_string(file_content, self.replace_file)
temp_file = tempfile.NamedTemporaryFile()
temp_file.write(file_content.encode())
temp_file.flush()
self.replace_file = cfg_filename
self._send_file(temp_file.name, cfg_filename)
def load_merge_candidate(self, filename=None, config=None):
self.replace = False
self.loaded = True
if not filename and not config:
raise MergeConfigException('filename or config param must be provided.')
self.merge_candidate += '\n' # insert one extra line
if filename is not None:
with open(filename, "r") as f:
self.merge_candidate += f.read()
else:
self.merge_candidate += config
def _send_file(self, filename, dest):
self.fc = FileCopy(self.device, filename, dst=dest.split('/')[-1])
try:
if not self.fc.remote_file_exists():
self.fc.send()
elif not self.fc.file_already_exists():
commands = ['terminal dont-ask',
'delete {0}'.format(self.fc.dst)]
self.device.config_list(commands)
self.fc.send()
except NXOSFileTransferError as fte:
raise ReplaceConfigException(py23_compat.text_type(fte))
def _create_sot_file(self):
"""Create Source of Truth file to compare."""
commands = ['terminal dont-ask', 'checkpoint file sot_file']
self.device.config_list(commands)
def _get_diff(self, cp_file):
"""Get a diff between running config and a proposed file."""
diff = []
self._create_sot_file()
diff_out = self.device.show(
'show diff rollback-patch file {0} file {1}'.format(
'sot_file', self.replace_file.split('/')[-1]), raw_text=True)
try:
diff_out = diff_out.split(
'Generating Rollback Patch')[1].replace(
'Rollback Patch is Empty', '').strip()
for line in diff_out.splitlines():
if line:
if line[0].strip() != '!':
diff.append(line.rstrip(' '))
except (AttributeError, KeyError):
raise ReplaceConfigException(
'Could not calculate diff. It\'s possible the given file doesn\'t exist.')
return '\n'.join(diff)
def _get_merge_diff(self):
diff = []
running_config = self.get_config(retrieve='running')['running']
running_lines = running_config.splitlines()
for line in self.merge_candidate.splitlines():
if line not in running_lines and line:
if line[0].strip() != '!':
diff.append(line)
return '\n'.join(diff)
# the merge diff is not necessarily what needs to be loaded
# for example under NTP, as the `ntp commit` command might be
# alread configured, it is mandatory to be sent
# otherwise it won't take the new configuration - see #59
# https://github.com/napalm-automation/napalm-nxos/issues/59
# therefore this method will return the real diff
# but the merge_candidate will remain unchanged
# previously: self.merge_candidate = '\n'.join(diff)
def compare_config(self):
if self.loaded:
if not self.replace:
return self._get_merge_diff()
# return self.merge_candidate
diff = self._get_diff(self.fc.dst)
return diff
return ''
def _copy_run_start(self, filename='startup-config'):
results = self.device.save(filename=filename)
if not results:
msg = 'Unable to save running-config to {}!'.format(filename)
raise CommandErrorException(msg)
def _commit_merge(self):
try:
commands = [command for command in self.merge_candidate.splitlines() if command]
self.device.config_list(commands)
except Exception as e:
raise MergeConfigException(str(e))
# clear the merge buffer
self.merge_candidate = ''
def _save_to_checkpoint(self, filename):
"""Save the current running config to the given file."""
command = 'checkpoint file {}'.format(filename)
self.device.show(command, raw_text=True)
def _disable_confirmation(self):
self.device.config('terminal dont-ask')
def _load_cfg_from_checkpoint(self):
cmd = 'rollback running file {0}'.format(self.replace_file.split('/')[-1])
self._disable_confirmation()
try:
rollback_result = self.device.config(cmd)
except ConnectionError:
# requests will raise an error with verbose warning output (don't fail on this).
return
if 'Rollback failed.' in rollback_result['msg'] or 'ERROR' in rollback_result:
raise ReplaceConfigException(rollback_result['msg'])
def _delete_file(self, filename):
commands = ['terminal dont-ask',
'delete {}'.format(filename),
'no terminal dont-ask']
self.device.show_list(commands, raw_text=True)
def discard_config(self):
if self.loaded:
self.merge_candidate = '' # clear the buffer
if self.loaded and self.replace:
try:
self._delete_file(self.fc.dst)
except CLIError:
pass
self.loaded = False
def rollback(self):
if self.changed:
self.device.rollback(self.backup_file)
self._copy_run_start()
self.changed = False
def get_facts(self):
pynxos_facts = self.device.facts
final_facts = {key: value for key, value in pynxos_facts.items() if
key not in ['interfaces', 'uptime_string', 'vlans']}
if pynxos_facts['interfaces']:
final_facts['interface_list'] = pynxos_facts['interfaces']
else:
final_facts['interface_list'] = self.get_interfaces().keys()
final_facts['vendor'] = 'Cisco'
hostname_cmd = 'show hostname'
hostname = self.device.show(hostname_cmd).get('hostname')
if hostname:
final_facts['fqdn'] = hostname
return final_facts
def get_interfaces(self):
interfaces = {}
iface_cmd = 'show interface'
interfaces_out = self.device.show(iface_cmd)
interfaces_body = interfaces_out['TABLE_interface']['ROW_interface']
for interface_details in interfaces_body:
interface_name = interface_details.get('interface')
# Earlier version of Nexus returned a list for 'eth_bw' (observed on 7.1(0)N1(1a))
interface_speed = interface_details.get('eth_bw', 0)
if isinstance(interface_speed, list):
interface_speed = interface_speed[0]
interface_speed = int(interface_speed / 1000)
if 'admin_state' in interface_details:
is_up = interface_details.get('admin_state', '') == 'up'
else:
is_up = interface_details.get('state', '') == 'up'
interfaces[interface_name] = {
'is_up': is_up,
'is_enabled': (interface_details.get('state') == 'up'),
'description': py23_compat.text_type(interface_details.get('desc', '').strip('"')),
'last_flapped': self._compute_timestamp(
interface_details.get('eth_link_flapped', '')),
'speed': interface_speed,
'mac_address': napalm.base.helpers.convert(
napalm.base.helpers.mac, interface_details.get('eth_hw_addr')),
}
return interfaces
def get_lldp_neighbors(self):
results = {}
try:
command = 'show lldp neighbors'
lldp_raw_output = self.cli([command]).get(command, '')
lldp_neighbors = napalm.base.helpers.textfsm_extractor(
self, 'lldp_neighbors', lldp_raw_output)
except CLIError:
lldp_neighbors = []
for neighbor in lldp_neighbors:
local_iface = neighbor.get('local_interface')
if neighbor.get(local_iface) is None:
if local_iface not in results:
results[local_iface] = []
neighbor_dict = {'hostname': py23_compat.text_type(neighbor.get('neighbor')),
'port': py23_compat.text_type(neighbor.get('neighbor_interface'))}
results[local_iface].append(neighbor_dict)
return results
def get_bgp_neighbors(self):
results = {}
bgp_state_dict = {
'Idle': {'is_up': False, 'is_enabled': True},
'Active': {'is_up': False, 'is_enabled': True},
'Open': {'is_up': False, 'is_enabled': True},
'Established': {'is_up': True, 'is_enabled': True},
'Closing': {'is_up': True, 'is_enabled': True},
'Shutdown': {'is_up': False, 'is_enabled': False},
}
try:
cmd = 'show bgp sessions vrf all'
vrf_list = self._get_command_table(cmd, 'TABLE_vrf', 'ROW_vrf')
except CLIError:
vrf_list = []
for vrf_dict in vrf_list:
result_vrf_dict = {
'router_id': py23_compat.text_type(vrf_dict['router-id']),
'peers': {}
}
neighbors_list = vrf_dict.get('TABLE_neighbor', {}).get('ROW_neighbor', [])
if isinstance(neighbors_list, dict):
neighbors_list = [neighbors_list]
for neighbor_dict in neighbors_list:
neighborid = napalm.base.helpers.ip(neighbor_dict['neighbor-id'])
remoteas = napalm.base.helpers.as_number(neighbor_dict['remoteas'])
state = py23_compat.text_type(neighbor_dict['state'])
bgp_state = bgp_state_dict[state]
result_peer_dict = {
'local_as': int(vrf_dict['local-as']),
'remote_as': remoteas,
'remote_id': neighborid,
'is_enabled': bgp_state['is_enabled'],
'uptime': -1,
'description': '',
'is_up': bgp_state['is_up'],
'address_family': {
'ipv4': {
'sent_prefixes': -1,
'accepted_prefixes': -1,
'received_prefixes': -1
}
}
}
result_vrf_dict['peers'][neighborid] = result_peer_dict
vrf_name = vrf_dict['vrf-name-out']
if vrf_name == 'default':
vrf_name = 'global'
results[vrf_name] = result_vrf_dict
return results
def _set_checkpoint(self, filename):
commands = ['terminal dont-ask', 'checkpoint file {0}'.format(filename)]
self.device.config_list(commands)
def _get_checkpoint_file(self):
filename = 'temp_cp_file_from_napalm'
self._set_checkpoint(filename)
cp_out = self.device.show('show file {0}'.format(filename), raw_text=True)
self._delete_file(filename)
return cp_out
def get_lldp_neighbors_detail(self, interface=''):
lldp_neighbors = {}
filter = ''
if interface:
filter = 'interface {name} '.format(name=interface)
command = 'show lldp neighbors {filter}detail'.format(filter=filter)
# seems that some old devices may not return JSON output...
try:
lldp_neighbors_table_str = self.cli([command]).get(command)
# thus we need to take the raw text output
lldp_neighbors_list = lldp_neighbors_table_str.splitlines()
except CLIError:
lldp_neighbors_list = []
if not lldp_neighbors_list:
return lldp_neighbors # empty dict
CHASSIS_REGEX = r'^(Chassis id:)\s+([a-z0-9\.]+)$'
PORT_REGEX = r'^(Port id:)\s+([0-9]+)$'
LOCAL_PORT_ID_REGEX = r'^(Local Port id:)\s+(.*)$'
PORT_DESCR_REGEX = r'^(Port Description:)\s+(.*)$'
SYSTEM_NAME_REGEX = r'^(System Name:)\s+(.*)$'
SYSTEM_DESCR_REGEX = r'^(System Description:)\s+(.*)$'
SYST_CAPAB_REEGX = r'^(System Capabilities:)\s+(.*)$'
ENABL_CAPAB_REGEX = r'^(Enabled Capabilities:)\s+(.*)$'
VLAN_ID_REGEX = r'^(Vlan ID:)\s+(.*)$'
lldp_neighbor = {}
interface_name = None
for line in lldp_neighbors_list:
chassis_rgx = re.search(CHASSIS_REGEX, line, re.I)
if chassis_rgx:
lldp_neighbor = {
'remote_chassis_id': napalm.base.helpers.mac(chassis_rgx.groups()[1])
}
continue
lldp_neighbor['parent_interface'] = ''
port_rgx = re.search(PORT_REGEX, line, re.I)
if port_rgx:
lldp_neighbor['parent_interface'] = py23_compat.text_type(port_rgx.groups()[1])
continue
local_port_rgx = re.search(LOCAL_PORT_ID_REGEX, line, re.I)
if local_port_rgx:
interface_name = local_port_rgx.groups()[1]
continue
port_descr_rgx = re.search(PORT_DESCR_REGEX, line, re.I)
if port_descr_rgx:
lldp_neighbor['remote_port'] = py23_compat.text_type(port_descr_rgx.groups()[1])
lldp_neighbor['remote_port_description'] = py23_compat.text_type(
port_descr_rgx.groups()[1])
continue
syst_name_rgx = re.search(SYSTEM_NAME_REGEX, line, re.I)
if syst_name_rgx:
lldp_neighbor['remote_system_name'] = py23_compat.text_type(
syst_name_rgx.groups()[1])
continue
syst_descr_rgx = re.search(SYSTEM_DESCR_REGEX, line, re.I)
if syst_descr_rgx:
lldp_neighbor['remote_system_description'] = py23_compat.text_type(
syst_descr_rgx.groups()[1])
continue
syst_capab_rgx = re.search(SYST_CAPAB_REEGX, line, re.I)
if syst_capab_rgx:
lldp_neighbor['remote_system_capab'] = py23_compat.text_type(
syst_capab_rgx.groups()[1])
continue
syst_enabled_rgx = re.search(ENABL_CAPAB_REGEX, line, re.I)
if syst_enabled_rgx:
lldp_neighbor['remote_system_enable_capab'] = py23_compat.text_type(
syst_enabled_rgx.groups()[1])
continue
vlan_rgx = re.search(VLAN_ID_REGEX, line, re.I)
if vlan_rgx:
# at the end of the loop
if interface_name not in lldp_neighbors.keys():
lldp_neighbors[interface_name] = []
lldp_neighbors[interface_name].append(lldp_neighbor)
return lldp_neighbors
def cli(self, commands):
cli_output = {}
if type(commands) is not list:
raise TypeError('Please enter a valid list of commands!')
for command in commands:
command_output = self.device.show(command, raw_text=True)
cli_output[py23_compat.text_type(command)] = command_output
return cli_output
def get_arp_table(self):
arp_table = []
command = 'show ip arp'
arp_table_vrf = self._get_command_table(command, 'TABLE_vrf', 'ROW_vrf')
arp_table_raw = self._get_table_rows(arp_table_vrf[0], 'TABLE_adj', 'ROW_adj')
for arp_table_entry in arp_table_raw:
raw_ip = arp_table_entry.get('ip-addr-out')
raw_mac = arp_table_entry.get('mac')
age = arp_table_entry.get('time-stamp')
if age == '-':
age_sec = -1.0
elif ':' not in age:
# Cisco sometimes returns a sub second arp time 0.411797
try:
age_sec = float(age)
except ValueError:
age_sec = -1.0
else:
fields = age.split(':')
if len(fields) == 3:
try:
fields = [float(x) for x in fields]
hours, minutes, seconds = fields
age_sec = 3600 * hours + 60 * minutes + seconds
except ValueError:
age_sec = -1.0
age_sec = round(age_sec, 1)
interface = py23_compat.text_type(arp_table_entry.get('intf-out'))
arp_table.append({
'interface': interface,
'mac': napalm.base.helpers.convert(
napalm.base.helpers.mac, raw_mac, raw_mac),
'ip': napalm.base.helpers.ip(raw_ip),
'age': age_sec
})
return arp_table
def _get_ntp_entity(self, peer_type):
ntp_entities = {}
command = 'show ntp peers'
ntp_peers_table = self._get_command_table(command, 'TABLE_peers', 'ROW_peers')
for ntp_peer in ntp_peers_table:
if ntp_peer.get('serv_peer', '').strip() != peer_type:
continue
peer_addr = napalm.base.helpers.ip(ntp_peer.get('PeerIPAddress').strip())
ntp_entities[peer_addr] = {}
return ntp_entities
def get_ntp_peers(self):
return self._get_ntp_entity('Peer')
def get_ntp_servers(self):
return self._get_ntp_entity('Server')
def get_ntp_stats(self):
ntp_stats = []
command = 'show ntp peer-status'
ntp_stats_table = self._get_command_table(command, 'TABLE_peersstatus', 'ROW_peersstatus')
for ntp_peer in ntp_stats_table:
peer_address = napalm.base.helpers.ip(ntp_peer.get('remote').strip())
syncmode = ntp_peer.get('syncmode')
stratum = int(ntp_peer.get('st'))
hostpoll = int(ntp_peer.get('poll'))
reachability = int(ntp_peer.get('reach'))
delay = float(ntp_peer.get('delay'))
ntp_stats.append({
'remote': peer_address,
'synchronized': (syncmode == '*'),
'referenceid': peer_address,
'stratum': stratum,
'type': '',
'when': '',
'hostpoll': hostpoll,
'reachability': reachability,
'delay': delay,
'offset': 0.0,
'jitter': 0.0
})
return ntp_stats
def get_interfaces_ip(self):
interfaces_ip = {}
ipv4_command = 'show ip interface vrf all'
ipv4_interf_table_vrf = self._get_command_table(ipv4_command, 'TABLE_intf', 'ROW_intf')
for interface in ipv4_interf_table_vrf:
interface_name = py23_compat.text_type(interface.get('intf-name', ''))
addr_str = interface.get('prefix')
unnumbered = py23_compat.text_type(interface.get('unnum-intf', ''))
if addr_str:
address = napalm.base.helpers.ip(addr_str)
prefix = int(interface.get('masklen', ''))
if interface_name not in interfaces_ip.keys():
interfaces_ip[interface_name] = {}
if 'ipv4' not in interfaces_ip[interface_name].keys():
interfaces_ip[interface_name]['ipv4'] = {}
if address not in interfaces_ip[interface_name].get('ipv4'):
interfaces_ip[interface_name]['ipv4'][address] = {}
interfaces_ip[interface_name]['ipv4'][address].update({
'prefix_length': prefix
})
elif unnumbered:
for interf in ipv4_interf_table_vrf:
interf_name = py23_compat.text_type(interf.get('intf-name', ''))
if interf_name == unnumbered:
address = napalm.base.helpers.ip(interf.get('prefix'))
prefix = int(interf.get('masklen', ''))
if interface_name not in interfaces_ip.keys():
interfaces_ip[interface_name] = {}
if 'ipv4' not in interfaces_ip[interface_name].keys():
interfaces_ip[interface_name]['ipv4'] = {}
if address not in interfaces_ip[interface_name].get('ipv4'):
interfaces_ip[interface_name]['ipv4'][address] = {}
interfaces_ip[interface_name]['ipv4'][address].update({
'prefix_length': prefix
})
secondary_addresses = interface.get('TABLE_secondary_address', {}) \
.get('ROW_secondary_address', [])
if type(secondary_addresses) is dict:
secondary_addresses = [secondary_addresses]
for secondary_address in secondary_addresses:
secondary_address_ip = napalm.base.helpers.ip(secondary_address.get('prefix1'))
secondary_address_prefix = int(secondary_address.get('masklen1', ''))
if 'ipv4' not in interfaces_ip[interface_name].keys():
interfaces_ip[interface_name]['ipv4'] = {}
if secondary_address_ip not in interfaces_ip[interface_name].get('ipv4'):
interfaces_ip[interface_name]['ipv4'][secondary_address_ip] = {}
interfaces_ip[interface_name]['ipv4'][secondary_address_ip].update({
'prefix_length': secondary_address_prefix
})
ipv6_command = 'show ipv6 interface vrf all'
ipv6_interf_table_vrf = self._get_command_table(ipv6_command, 'TABLE_intf', 'ROW_intf')
for interface in ipv6_interf_table_vrf:
interface_name = py23_compat.text_type(interface.get('intf-name', ''))
if interface_name not in interfaces_ip.keys():
interfaces_ip[interface_name] = {}
if 'ipv6' not in interfaces_ip[interface_name].keys():
interfaces_ip[interface_name]['ipv6'] = {}
if type(interface.get('addr', '')) is list:
for ipv6_address in interface.get('addr', ''):
address = napalm.base.helpers.ip(ipv6_address.split('/')[0])
prefix = int(ipv6_address.split('/')[-1])
if address not in interfaces_ip[interface_name].get('ipv6'):
interfaces_ip[interface_name]['ipv6'][address] = {}
interfaces_ip[interface_name]['ipv6'][address].update({
'prefix_length': prefix
})
else:
address = napalm.base.helpers.ip(interface.get('addr', '').split('/')[0])
prefix = interface.get('prefix', '').split('/')[-1]
if prefix:
prefix = int(interface.get('prefix', '').split('/')[-1])
else:
prefix = 128
if address not in interfaces_ip[interface_name].get('ipv6'):
interfaces_ip[interface_name]['ipv6'][address] = {}
interfaces_ip[interface_name]['ipv6'][address].update({
'prefix_length': prefix
})
return interfaces_ip
def get_mac_address_table(self):
mac_table = []
command = 'show mac address-table'
mac_table_raw = self._get_command_table(command, 'TABLE_mac_address', 'ROW_mac_address')
for mac_entry in mac_table_raw:
raw_mac = mac_entry.get('disp_mac_addr')
interface = py23_compat.text_type(mac_entry.get('disp_port'))
vlan = int(mac_entry.get('disp_vlan'))
active = True
static = (mac_entry.get('disp_is_static') != '0')
moves = 0
last_move = 0.0
mac_table.append({
'mac': napalm.base.helpers.mac(raw_mac),
'interface': interface,
'vlan': vlan,
'active': active,
'static': static,
'moves': moves,
'last_move': last_move
})
return mac_table
def get_snmp_information(self):
snmp_information = {}
snmp_command = 'show running-config'
snmp_raw_output = self.cli([snmp_command]).get(snmp_command, '')
snmp_config = napalm.base.helpers.textfsm_extractor(self, 'snmp_config', snmp_raw_output)
if not snmp_config:
return snmp_information
snmp_information = {
'contact': py23_compat.text_type(''),
'location': py23_compat.text_type(''),
'community': {},
'chassis_id': py23_compat.text_type('')
}
for snmp_entry in snmp_config:
contact = py23_compat.text_type(snmp_entry.get('contact', ''))
if contact:
snmp_information['contact'] = contact
location = py23_compat.text_type(snmp_entry.get('location', ''))
if location:
snmp_information['location'] = location
community_name = py23_compat.text_type(snmp_entry.get('community', ''))
if not community_name:
continue
if community_name not in snmp_information['community'].keys():
snmp_information['community'][community_name] = {
'acl': py23_compat.text_type(snmp_entry.get('acl', '')),
'mode': py23_compat.text_type(snmp_entry.get('mode', '').lower())
}
else:
acl = py23_compat.text_type(snmp_entry.get('acl', ''))
if acl:
snmp_information['community'][community_name]['acl'] = acl
mode = py23_compat.text_type(snmp_entry.get('mode', '').lower())
if mode:
snmp_information['community'][community_name]['mode'] = mode
return snmp_information
def get_users(self):
_CISCO_TO_CISCO_MAP = {
'network-admin': 15,
'network-operator': 5
}
_DEFAULT_USER_DICT = {
'password': '',
'level': 0,
'sshkeys': []
}
users = {}
command = 'show running-config'
section_username_raw_output = self.cli([command]).get(command, '')
section_username_tabled_output = napalm.base.helpers.textfsm_extractor(
self, 'users', section_username_raw_output)
for user in section_username_tabled_output:
username = user.get('username', '')
if not username:
continue
if username not in users:
users[username] = _DEFAULT_USER_DICT.copy()
password = user.get('password', '')
if password:
users[username]['password'] = py23_compat.text_type(password.strip())
level = 0
role = user.get('role', '')
if role.startswith('priv'):
level = int(role.split('-')[-1])
else:
level = _CISCO_TO_CISCO_MAP.get(role, 0)
if level > users.get(username).get('level'):
# unfortunately on Cisco you can set different priv levels for the same user
# Good news though: the device will consider the highest level
users[username]['level'] = level