This repository has been archived by the owner on Jan 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 40
/
ios.py
2185 lines (1927 loc) · 92.2 KB
/
ios.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
"""NAPALM Cisco IOS Handler."""
# 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 print_function
from __future__ import unicode_literals
import re
import os
import uuid
import socket
import tempfile
import telnetlib
import copy
from netmiko import ConnectHandler, FileTransfer, InLineTransfer
from napalm_base.base import NetworkDriver
from napalm_base.exceptions import ReplaceConfigException, MergeConfigException, \
ConnectionClosedException, CommandErrorException
from napalm_base.utils import py23_compat
import napalm_base.constants as C
import napalm_base.helpers
# Easier to store these as constants
HOUR_SECONDS = 3600
DAY_SECONDS = 24 * HOUR_SECONDS
WEEK_SECONDS = 7 * DAY_SECONDS
YEAR_SECONDS = 365 * DAY_SECONDS
# STD REGEX PATTERNS
IP_ADDR_REGEX = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
IPV4_ADDR_REGEX = IP_ADDR_REGEX
IPV6_ADDR_REGEX_1 = r"::"
IPV6_ADDR_REGEX_2 = r"[0-9a-fA-F:]{1,39}::[0-9a-fA-F:]{1,39}"
IPV6_ADDR_REGEX_3 = r"[0-9a-fA-F]{1,3}:[0-9a-fA-F]{1,3}:[0-9a-fA-F]{1,3}:[0-9a-fA-F]{1,3}:" \
"[0-9a-fA-F]{1,3}:[0-9a-fA-F]{1,3}:[0-9a-fA-F]{1,3}:[0-9a-fA-F]{1,3}"
# Should validate IPv6 address using an IP address library after matching with this regex
IPV6_ADDR_REGEX = "(?:{}|{}|{})".format(IPV6_ADDR_REGEX_1, IPV6_ADDR_REGEX_2, IPV6_ADDR_REGEX_3)
MAC_REGEX = r"[a-fA-F0-9]{4}\.[a-fA-F0-9]{4}\.[a-fA-F0-9]{4}"
VLAN_REGEX = r"\d{1,4}"
RE_IPADDR = re.compile(r"{}".format(IP_ADDR_REGEX))
RE_IPADDR_STRIP = re.compile(r"({})\n".format(IP_ADDR_REGEX))
RE_MAC = re.compile(r"{}".format(MAC_REGEX))
# Period needed for 32-bit AS Numbers
ASN_REGEX = r"[\d\.]+"
IOS_COMMANDS = {
'show_mac_address': ['show mac-address-table', 'show mac address-table'],
}
class IOSDriver(NetworkDriver):
"""NAPALM Cisco IOS Handler."""
def __init__(self, hostname, username, password, timeout=60, optional_args=None):
"""NAPALM Cisco IOS Handler."""
if optional_args is None:
optional_args = {}
self.hostname = hostname
self.username = username
self.password = password
self.timeout = timeout
self.transport = optional_args.get('transport', 'ssh')
# Retrieve file names
self.candidate_cfg = optional_args.get('candidate_cfg', 'candidate_config.txt')
self.merge_cfg = optional_args.get('merge_cfg', 'merge_config.txt')
self.rollback_cfg = optional_args.get('rollback_cfg', 'rollback_config.txt')
self.inline_transfer = optional_args.get('inline_transfer', False)
if self.transport == 'telnet':
# Telnet only supports inline_transfer
self.inline_transfer = True
# None will cause autodetection of dest_file_system
self._dest_file_system = optional_args.get('dest_file_system', None)
self.auto_rollback_on_error = optional_args.get('auto_rollback_on_error', True)
# Netmiko possible arguments
netmiko_argument_map = {
'port': None,
'secret': '',
'verbose': False,
'keepalive': 30,
'global_delay_factor': 1,
'use_keys': False,
'key_file': None,
'ssh_strict': False,
'system_host_keys': False,
'alt_host_keys': False,
'alt_key_file': '',
'ssh_config_file': None,
'allow_agent': False,
}
# Build dict of any optional Netmiko args
self.netmiko_optional_args = {}
for k, v in netmiko_argument_map.items():
try:
self.netmiko_optional_args[k] = optional_args[k]
except KeyError:
pass
default_port = {
'ssh': 22,
'telnet': 23
}
self.port = optional_args.get('port', default_port[self.transport])
self.device = None
self.config_replace = False
self.interface_map = {}
self.profile = ["ios"]
def open(self):
"""Open a connection to the device."""
device_type = 'cisco_ios'
if self.transport == 'telnet':
device_type = 'cisco_ios_telnet'
self.device = ConnectHandler(device_type=device_type,
host=self.hostname,
username=self.username,
password=self.password,
**self.netmiko_optional_args)
# ensure in enable mode
self.device.enable()
def _discover_file_system(self):
try:
return self.device._autodetect_fs()
except Exception:
msg = "Netmiko _autodetect_fs failed (to workaround specify " \
"dest_file_system in optional_args.)"
raise CommandErrorException(msg)
def close(self):
"""Close the connection to the device."""
self.device.disconnect()
def _send_command(self, command):
"""Wrapper for self.device.send.command().
If command is a list will iterate through commands until valid command.
"""
try:
if isinstance(command, list):
for cmd in command:
output = self.device.send_command(cmd)
if "% Invalid" not in output:
break
else:
output = self.device.send_command(command)
return self._send_command_postprocess(output)
except (socket.error, EOFError) as e:
raise ConnectionClosedException(str(e))
def is_alive(self):
"""Returns a flag with the state of the connection."""
null = chr(0)
if self.device is None:
return {'is_alive': False}
if self.transport == 'telnet':
try:
# Try sending IAC + NOP (IAC is telnet way of sending command
# IAC = Interpret as Command (it comes before the NOP)
self.device.write_channel(telnetlib.IAC + telnetlib.NOP)
return {'is_alive': True}
except UnicodeDecodeError:
# Netmiko logging bug (remove after Netmiko >= 1.4.3)
return {'is_alive': True}
except AttributeError:
return {'is_alive': False}
else:
# SSH
try:
# Try sending ASCII null byte to maintain the connection alive
self.device.write_channel(null)
return {'is_alive': self.device.remote_conn.transport.is_active()}
except (socket.error, EOFError):
# If unable to send, we can tell for sure that the connection is unusable
return {'is_alive': False}
return {'is_alive': False}
@staticmethod
def _create_tmp_file(config):
"""Write temp file and for use with inline config and SCP."""
tmp_dir = tempfile.gettempdir()
rand_fname = py23_compat.text_type(uuid.uuid4())
filename = os.path.join(tmp_dir, rand_fname)
with open(filename, 'wt') as fobj:
fobj.write(config)
return filename
def _load_candidate_wrapper(self, source_file=None, source_config=None, dest_file=None,
file_system=None):
"""
Transfer file to remote device for either merge or replace operations
Returns (return_status, msg)
"""
return_status = False
msg = ''
if source_file and source_config:
raise ValueError("Cannot simultaneously set source_file and source_config")
if source_config:
if self.inline_transfer:
(return_status, msg) = self._inline_tcl_xfer(source_config=source_config,
dest_file=dest_file,
file_system=file_system)
else:
# Use SCP
tmp_file = self._create_tmp_file(source_config)
(return_status, msg) = self._scp_file(source_file=tmp_file, dest_file=dest_file,
file_system=file_system)
if tmp_file and os.path.isfile(tmp_file):
os.remove(tmp_file)
if source_file:
if self.inline_transfer:
(return_status, msg) = self._inline_tcl_xfer(source_file=source_file,
dest_file=dest_file,
file_system=file_system)
else:
(return_status, msg) = self._scp_file(source_file=source_file, dest_file=dest_file,
file_system=file_system)
if not return_status:
if msg == '':
msg = "Transfer to remote device failed"
return (return_status, msg)
def load_replace_candidate(self, filename=None, config=None):
"""
SCP file to device filesystem, defaults to candidate_config.
Return None or raise exception
"""
self.config_replace = True
return_status, msg = self._load_candidate_wrapper(source_file=filename,
source_config=config,
dest_file=self.candidate_cfg,
file_system=self.dest_file_system)
if not return_status:
raise ReplaceConfigException(msg)
def load_merge_candidate(self, filename=None, config=None):
"""
SCP file to remote device.
Merge configuration in: copy <file> running-config
"""
self.config_replace = False
return_status, msg = self._load_candidate_wrapper(source_file=filename,
source_config=config,
dest_file=self.merge_cfg,
file_system=self.dest_file_system)
if not return_status:
raise MergeConfigException(msg)
@staticmethod
def _normalize_compare_config(diff):
"""Filter out strings that should not show up in the diff."""
ignore_strings = ['Contextual Config Diffs', 'No changes were found',
'file prompt quiet', 'ntp clock-period']
new_list = []
for line in diff.splitlines():
for ignore in ignore_strings:
if ignore in line:
break
else: # nobreak
new_list.append(line)
return "\n".join(new_list)
@staticmethod
def _normalize_merge_diff_incr(diff):
"""Make the compare config output look better.
Cisco IOS incremental-diff output
No changes:
!List of Commands:
end
!No changes were found
"""
new_diff = []
changes_found = False
for line in diff.splitlines():
if re.search(r'order-dependent line.*re-ordered', line):
changes_found = True
elif 'No changes were found' in line:
# IOS in the re-order case still claims "No changes were found"
if not changes_found:
return ''
else:
continue
if line.strip() == 'end':
continue
elif 'List of Commands' in line:
continue
# Filter blank lines and prepend +sign
elif line.strip():
if re.search(r"^no\s+", line.strip()):
new_diff.append('-' + line)
else:
new_diff.append('+' + line)
return "\n".join(new_diff)
@staticmethod
def _normalize_merge_diff(diff):
"""Make compare_config() for merge look similar to replace config diff."""
new_diff = []
for line in diff.splitlines():
# Filter blank lines and prepend +sign
if line.strip():
new_diff.append('+' + line)
if new_diff:
new_diff.insert(0, '! incremental-diff failed; falling back to echo of merge file')
else:
new_diff.append('! No changes specified in merge file.')
return "\n".join(new_diff)
def compare_config(self):
"""
show archive config differences <base_file> <new_file>.
Default operation is to compare system:running-config to self.candidate_cfg
"""
# Set defaults
base_file = 'running-config'
base_file_system = 'system:'
if self.config_replace:
new_file = self.candidate_cfg
else:
new_file = self.merge_cfg
new_file_system = self.dest_file_system
base_file_full = self._gen_full_path(filename=base_file, file_system=base_file_system)
new_file_full = self._gen_full_path(filename=new_file, file_system=new_file_system)
if self.config_replace:
cmd = 'show archive config differences {} {}'.format(base_file_full, new_file_full)
diff = self.device.send_command_expect(cmd)
diff = self._normalize_compare_config(diff)
else:
# merge
cmd = 'show archive config incremental-diffs {} ignorecase'.format(new_file_full)
diff = self.device.send_command_expect(cmd)
if 'error code 5' in diff or 'returned error 5' in diff:
diff = "You have encountered the obscure 'error 5' message. This generally " \
"means you need to add an 'end' statement to the end of your merge changes."
elif '% Invalid' not in diff:
diff = self._normalize_merge_diff_incr(diff)
else:
cmd = 'more {}'.format(new_file_full)
diff = self.device.send_command_expect(cmd)
diff = self._normalize_merge_diff(diff)
return diff.strip()
def _commit_hostname_handler(self, cmd):
"""Special handler for hostname change on commit operation."""
current_prompt = self.device.find_prompt().strip()
terminating_char = current_prompt[-1]
pattern = r"[>#{}]\s*$".format(terminating_char)
# Look exclusively for trailing pattern that includes '#' and '>'
output = self.device.send_command_expect(cmd, expect_string=pattern)
# Reset base prompt in case hostname changed
self.device.set_base_prompt()
return output
def commit_config(self):
"""
If replacement operation, perform 'configure replace' for the entire config.
If merge operation, perform copy <file> running-config.
"""
# Always generate a rollback config on commit
self._gen_rollback_cfg()
if self.config_replace:
# Replace operation
filename = self.candidate_cfg
cfg_file = self._gen_full_path(filename)
if not self._check_file_exists(cfg_file):
raise ReplaceConfigException("Candidate config file does not exist")
if self.auto_rollback_on_error:
cmd = 'configure replace {} force revert trigger error'.format(cfg_file)
else:
cmd = 'configure replace {} force'.format(cfg_file)
output = self._commit_hostname_handler(cmd)
if ('original configuration has been successfully restored' in output) or \
('error' in output.lower()) or \
('failed' in output.lower()):
msg = "Candidate config could not be applied\n{}".format(output)
raise ReplaceConfigException(msg)
elif '%Please turn config archive on' in output:
msg = "napalm-ios replace() requires Cisco 'archive' feature to be enabled."
raise ReplaceConfigException(msg)
else:
# Merge operation
filename = self.merge_cfg
cfg_file = self._gen_full_path(filename)
if not self._check_file_exists(cfg_file):
raise MergeConfigException("Merge source config file does not exist")
cmd = 'copy {} running-config'.format(cfg_file)
self._disable_confirm()
output = self._commit_hostname_handler(cmd)
self._enable_confirm()
if 'Invalid input detected' in output:
self.rollback()
err_header = "Configuration merge failed; automatic rollback attempted"
merge_error = "{0}:\n{1}".format(err_header, output)
raise MergeConfigException(merge_error)
# Save config to startup (both replace and merge)
output += self.device.send_command_expect("write mem")
def discard_config(self):
"""Set candidate_cfg to current running-config. Erase the merge_cfg file."""
discard_candidate = 'copy running-config {}'.format(self._gen_full_path(self.candidate_cfg))
discard_merge = 'copy null: {}'.format(self._gen_full_path(self.merge_cfg))
self._disable_confirm()
self.device.send_command_expect(discard_candidate)
self.device.send_command_expect(discard_merge)
self._enable_confirm()
def rollback(self):
"""Rollback configuration to filename or to self.rollback_cfg file."""
filename = self.rollback_cfg
cfg_file = self._gen_full_path(filename)
if not self._check_file_exists(cfg_file):
raise ReplaceConfigException("Rollback config file does not exist")
cmd = 'configure replace {} force'.format(cfg_file)
self.device.send_command_expect(cmd)
# Save config to startup
self.device.send_command_expect("write mem")
def _inline_tcl_xfer(self, source_file=None, source_config=None, dest_file=None,
file_system=None):
"""
Use Netmiko InlineFileTransfer (TCL) to transfer file or config to remote device.
Return (status, msg)
status = boolean
msg = details on what happened
"""
if source_file:
return self._xfer_file(source_file=source_file, dest_file=dest_file,
file_system=file_system, TransferClass=InLineTransfer)
if source_config:
return self._xfer_file(source_config=source_config, dest_file=dest_file,
file_system=file_system, TransferClass=InLineTransfer)
raise ValueError("File source not specified for transfer.")
def _scp_file(self, source_file, dest_file, file_system):
"""
SCP file to remote device.
Return (status, msg)
status = boolean
msg = details on what happened
"""
return self._xfer_file(source_file=source_file, dest_file=dest_file,
file_system=file_system, TransferClass=FileTransfer)
def _xfer_file(self, source_file=None, source_config=None, dest_file=None, file_system=None,
TransferClass=FileTransfer):
"""Transfer file to remote device.
By default, this will use Secure Copy if self.inline_transfer is set, then will use
Netmiko InlineTransfer method to transfer inline using either SSH or telnet (plus TCL
onbox).
Return (status, msg)
status = boolean
msg = details on what happened
"""
if not source_file and not source_config:
raise ValueError("File source not specified for transfer.")
if not dest_file or not file_system:
raise ValueError("Destination file or file system not specified.")
if source_file:
kwargs = dict(ssh_conn=self.device, source_file=source_file, dest_file=dest_file,
direction='put', file_system=file_system)
elif source_config:
kwargs = dict(ssh_conn=self.device, source_config=source_config, dest_file=dest_file,
direction='put', file_system=file_system)
enable_scp = True
if self.inline_transfer:
enable_scp = False
with TransferClass(**kwargs) as transfer:
# Check if file already exists and has correct MD5
if transfer.check_file_exists() and transfer.compare_md5():
msg = "File already exists and has correct MD5: no SCP needed"
return (True, msg)
if not transfer.verify_space_available():
msg = "Insufficient space available on remote device"
return (False, msg)
if enable_scp:
transfer.enable_scp()
# Transfer file
transfer.transfer_file()
# Compares MD5 between local-remote files
if transfer.verify_file():
msg = "File successfully transferred to remote device"
return (True, msg)
else:
msg = "File transfer to remote device failed"
return (False, msg)
return (False, '')
def _enable_confirm(self):
"""Enable IOS confirmations on file operations (global config command)."""
cmd = 'no file prompt quiet'
self.device.send_config_set([cmd])
def _disable_confirm(self):
"""Disable IOS confirmations on file operations (global config command)."""
cmd = 'file prompt quiet'
self.device.send_config_set([cmd])
def _gen_full_path(self, filename, file_system=None):
"""Generate full file path on remote device."""
if file_system is None:
return '{}/{}'.format(self.dest_file_system, filename)
else:
if ":" not in file_system:
raise ValueError("Invalid file_system specified: {}".format(file_system))
return '{}/{}'.format(file_system, filename)
def _gen_rollback_cfg(self):
"""Save a configuration that can be used for rollback."""
cfg_file = self._gen_full_path(self.rollback_cfg)
cmd = 'copy running-config {}'.format(cfg_file)
self._disable_confirm()
self.device.send_command_expect(cmd)
self._enable_confirm()
def _check_file_exists(self, cfg_file):
"""
Check that the file exists on remote device using full path.
cfg_file is full path i.e. flash:/file_name
For example
# dir flash:/candidate_config.txt
Directory of flash:/candidate_config.txt
33 -rw- 5592 Dec 18 2015 10:50:22 -08:00 candidate_config.txt
return boolean
"""
cmd = 'dir {}'.format(cfg_file)
success_pattern = 'Directory of {}'.format(cfg_file)
output = self.device.send_command_expect(cmd)
if 'Error opening' in output:
return False
elif success_pattern in output:
return True
return False
def _expand_interface_name(self, interface_brief):
"""
Obtain the full interface name from the abbreviated name.
Cache mappings in self.interface_map.
"""
if self.interface_map.get(interface_brief):
return self.interface_map.get(interface_brief)
command = 'show int {}'.format(interface_brief)
output = self._send_command(command)
first_line = output.splitlines()[0]
if 'line protocol' in first_line:
full_int_name = first_line.split()[0]
self.interface_map[interface_brief] = full_int_name
return self.interface_map.get(interface_brief)
else:
return interface_brief
@staticmethod
def _send_command_postprocess(output):
"""
Cleanup actions on send_command() for NAPALM getters.
Remove "Load for five sec; one minute if in output"
Remove "Time source is"
"""
output = re.sub(r"^Load for five secs.*$", "", output, flags=re.M)
output = re.sub(r"^Time source is .*$", "", output, flags=re.M)
return output.strip()
def get_optics(self):
command = 'show interfaces transceiver'
output = self._send_command(command)
# Check if router supports the command
if '% Invalid input' in output:
return {}
# Formatting data into return data structure
optics_detail = {}
try:
split_output = re.split(r'^---------.*$', output, flags=re.M)[1]
except IndexError:
return {}
split_output = split_output.strip()
for optics_entry in split_output.splitlines():
# Example, Te1/0/1 34.6 3.29 -2.0 -3.5
try:
split_list = optics_entry.split()
except ValueError:
return {}
int_brief = split_list[0]
output_power = split_list[3]
input_power = split_list[4]
port = self._expand_interface_name(int_brief)
port_detail = {}
port_detail['physical_channels'] = {}
port_detail['physical_channels']['channel'] = []
# If interface is shutdown it returns "N/A" as output power.
# Converting that to -100.0 float
try:
float(output_power)
except ValueError:
output_power = -100.0
# Defaulting avg, min, max values to -100.0 since device does not
# return these values
optic_states = {
'index': 0,
'state': {
'input_power': {
'instant': (float(input_power) if 'input_power' else -100.0),
'avg': -100.0,
'min': -100.0,
'max': -100.0
},
'output_power': {
'instant': (float(output_power) if 'output_power' else -100.0),
'avg': -100.0,
'min': -100.0,
'max': -100.0
},
'laser_bias_current': {
'instant': 0.0,
'avg': 0.0,
'min': 0.0,
'max': 0.0
}
}
}
port_detail['physical_channels']['channel'].append(optic_states)
optics_detail[port] = port_detail
return optics_detail
def get_lldp_neighbors(self):
"""IOS implementation of get_lldp_neighbors."""
lldp = {}
command = 'show lldp neighbors'
output = self._send_command(command)
# Check if router supports the command
if '% Invalid input' in output:
return {}
# Process the output to obtain just the LLDP entries
try:
split_output = re.split(r'^Device ID.*$', output, flags=re.M)[1]
split_output = re.split(r'^Total entries displayed.*$', split_output, flags=re.M)[0]
except IndexError:
return {}
split_output = split_output.strip()
for lldp_entry in split_output.splitlines():
# Example, twb-sf-hpsw1 Fa4 120 B 17
try:
device_id, local_int_brief, hold_time, capability, remote_port = lldp_entry.split()
except ValueError:
if len(lldp_entry.split()) == 4:
# Four fields might be long_name or missing capability
capability_missing = True if lldp_entry[46] == ' ' else False
if capability_missing:
device_id, local_int_brief, hold_time, remote_port = lldp_entry.split()
else:
# Might be long_name issue
tmp_field, hold_time, capability, remote_port = lldp_entry.split()
device_id = tmp_field[:20]
local_int_brief = tmp_field[20:]
# device_id might be abbreviated, try to get full name
lldp_tmp = self._lldp_detail_parser(local_int_brief)
device_id_new = lldp_tmp[3][0]
# Verify abbreviated and full name are consistent
if device_id_new[:20] == device_id:
device_id = device_id_new
else:
raise ValueError("Unable to obtain remote device name")
local_port = self._expand_interface_name(local_int_brief)
entry = {'port': remote_port, 'hostname': device_id}
lldp.setdefault(local_port, [])
lldp[local_port].append(entry)
return lldp
def _lldp_detail_parser(self, interface):
command = "show lldp neighbors {} detail".format(interface)
output = self._send_command(command)
# Check if router supports the command
if '% Invalid input' in output:
raise ValueError("Command not supported by network device")
# Cisco generally use : for string divider, but sometimes has ' - '
port_id = re.findall(r"Port id\s*?[:-]\s+(.+)", output)
port_description = re.findall(r"Port Description\s*?[:-]\s+(.+)", output)
chassis_id = re.findall(r"Chassis id\s*?[:-]\s+(.+)", output)
system_name = re.findall(r"System Name\s*?[:-]\s+(.+)", output)
system_description = re.findall(r"System Description\s*?[:-]\s*(not advertised|\s*\n.+)",
output)
system_description = [x.strip() for x in system_description]
system_capabilities = re.findall(r"System Capabilities\s*?[:-]\s+(.+)", output)
enabled_capabilities = re.findall(r"Enabled Capabilities\s*?[:-]\s+(.+)", output)
remote_address = re.findall(r"Management Addresses\s*[:-]\s*(not advertised|\n.+)", output)
# remote address had two possible patterns which required some secondary processing
new_remote_address = []
for val in remote_address:
val = val.strip()
pattern = r'(?:IP|Other)(?::\s+?)(.+)'
match = re.search(pattern, val)
if match:
new_remote_address.append(match.group(1))
else:
new_remote_address.append(val)
remote_address = new_remote_address
return [port_id, port_description, chassis_id, system_name, system_description,
system_capabilities, enabled_capabilities, remote_address]
def get_lldp_neighbors_detail(self, interface=''):
"""
IOS implementation of get_lldp_neighbors_detail.
Calls get_lldp_neighbors.
"""
lldp = {}
lldp_neighbors = self.get_lldp_neighbors()
# Filter to specific interface
if interface:
lldp_data = lldp_neighbors.get(interface)
if lldp_data:
lldp_neighbors = {interface: lldp_data}
else:
lldp_neighbors = {}
for interface in lldp_neighbors:
local_port = interface
lldp_fields = self._lldp_detail_parser(interface)
# Convert any 'not advertised' to 'N/A'
for field in lldp_fields:
for i, value in enumerate(field):
if 'not advertised' in value:
field[i] = 'N/A'
number_entries = len(lldp_fields[0])
# re.findall will return a list. Make sure same number of entries always returned.
for test_list in lldp_fields:
if len(test_list) != number_entries:
raise ValueError("Failure processing show lldp neighbors detail")
# Standardize the fields
port_id, port_description, chassis_id, system_name, system_description, \
system_capabilities, enabled_capabilities, remote_address = lldp_fields
standardized_fields = zip(port_id, port_description, chassis_id, system_name,
system_description, system_capabilities,
enabled_capabilities, remote_address)
lldp.setdefault(local_port, [])
for entry in standardized_fields:
remote_port_id, remote_port_description, remote_chassis_id, remote_system_name, \
remote_system_description, remote_system_capab, remote_enabled_capab, \
remote_mgmt_address = entry
lldp[local_port].append({
'parent_interface': u'N/A',
'remote_port': remote_port_id,
'remote_port_description': remote_port_description,
'remote_chassis_id': remote_chassis_id,
'remote_system_name': remote_system_name,
'remote_system_description': remote_system_description,
'remote_system_capab': remote_system_capab,
'remote_system_enable_capab': remote_enabled_capab})
return lldp
@staticmethod
def parse_uptime(uptime_str):
"""
Extract the uptime string from the given Cisco IOS Device.
Return the uptime in seconds as an integer
"""
# Initialize to zero
(years, weeks, days, hours, minutes) = (0, 0, 0, 0, 0)
uptime_str = uptime_str.strip()
time_list = uptime_str.split(',')
for element in time_list:
if re.search("year", element):
years = int(element.split()[0])
elif re.search("week", element):
weeks = int(element.split()[0])
elif re.search("day", element):
days = int(element.split()[0])
elif re.search("hour", element):
hours = int(element.split()[0])
elif re.search("minute", element):
minutes = int(element.split()[0])
uptime_sec = (years * YEAR_SECONDS) + (weeks * WEEK_SECONDS) + (days * DAY_SECONDS) + \
(hours * 3600) + (minutes * 60)
return uptime_sec
def get_facts(self):
"""Return a set of facts from the devices."""
# default values.
vendor = u'Cisco'
uptime = -1
serial_number, fqdn, os_version, hostname, domain_name = ('Unknown',) * 5
# obtain output from device
show_ver = self._send_command('show version')
show_hosts = self._send_command('show hosts')
show_ip_int_br = self._send_command('show ip interface brief')
# uptime/serial_number/IOS version
for line in show_ver.splitlines():
if ' uptime is ' in line:
hostname, uptime_str = line.split(' uptime is ')
uptime = self.parse_uptime(uptime_str)
hostname = hostname.strip()
if 'Processor board ID' in line:
_, serial_number = line.split("Processor board ID ")
serial_number = serial_number.strip()
if re.search(r"Cisco IOS Software", line):
try:
_, os_version = line.split("Cisco IOS Software, ")
except ValueError:
# Handle 'Cisco IOS Software [Denali],'
_, os_version = re.split(r"Cisco IOS Software \[.*?\], ", line)
os_version = os_version.strip()
elif re.search(r"IOS (tm).+Software", line):
_, os_version = line.split("IOS (tm) ")
os_version = os_version.strip()
# Determine domain_name and fqdn
for line in show_hosts.splitlines():
if 'Default domain' in line:
_, domain_name = line.split("Default domain is ")
domain_name = domain_name.strip()
break
if domain_name != 'Unknown' and hostname != 'Unknown':
fqdn = u'{}.{}'.format(hostname, domain_name)
# model filter
try:
match_model = re.search(r"Cisco (.+?) .+bytes of", show_ver, flags=re.IGNORECASE)
model = match_model.group(1)
except AttributeError:
model = u'Unknown'
# interface_list filter
interface_list = []
show_ip_int_br = show_ip_int_br.strip()
for line in show_ip_int_br.splitlines():
if 'Interface ' in line:
continue
interface = line.split()[0]
interface_list.append(interface)
return {
'uptime': uptime,
'vendor': vendor,
'os_version': py23_compat.text_type(os_version),
'serial_number': py23_compat.text_type(serial_number),
'model': py23_compat.text_type(model),
'hostname': py23_compat.text_type(hostname),
'fqdn': fqdn,
'interface_list': interface_list
}
def get_interfaces(self):
"""
Get interface details.
last_flapped is not implemented
Example Output:
{ u'Vlan1': { 'description': u'N/A',
'is_enabled': True,
'is_up': True,
'last_flapped': -1.0,
'mac_address': u'a493.4cc1.67a7',
'speed': 100},
u'Vlan100': { 'description': u'Data Network',
'is_enabled': True,
'is_up': True,
'last_flapped': -1.0,
'mac_address': u'a493.4cc1.67a7',
'speed': 100},
u'Vlan200': { 'description': u'Voice Network',
'is_enabled': True,
'is_up': True,
'last_flapped': -1.0,
'mac_address': u'a493.4cc1.67a7',
'speed': 100}}
"""
# default values.
last_flapped = -1.0
command = 'show interfaces'
output = self._send_command(command)
interface = description = mac_address = speed = speedformat = ''
is_enabled = is_up = None
interface_dict = {}
for line in output.splitlines():
interface_regex_1 = r"^(\S+?)\s+is\s+(.+?),\s+line\s+protocol\s+is\s+(\S+)"
interface_regex_2 = r"^(\S+)\s+is\s+(up|down)"
for pattern in (interface_regex_1, interface_regex_2):
interface_match = re.search(pattern, line)
if interface_match:
interface = interface_match.group(1)
status = interface_match.group(2)
try:
protocol = interface_match.group(3)
except IndexError:
protocol = ''
if 'admin' in status.lower():
is_enabled = False
else:
is_enabled = True
if protocol:
is_up = bool('up' in protocol)
else:
is_up = bool('up' in status)
break
mac_addr_regex = r"^\s+Hardware.+address\s+is\s+({})".format(MAC_REGEX)
if re.search(mac_addr_regex, line):
mac_addr_match = re.search(mac_addr_regex, line)
mac_address = napalm_base.helpers.mac(mac_addr_match.groups()[0])
descr_regex = "^\s+Description:\s+(.+?)$"
if re.search(descr_regex, line):
descr_match = re.search(descr_regex, line)
description = descr_match.groups()[0]
speed_regex = r"^\s+MTU\s+\d+.+BW\s+(\d+)\s+([KMG]?b)"
if re.search(speed_regex, line):
speed_match = re.search(speed_regex, line)