-
Notifications
You must be signed in to change notification settings - Fork 31
/
huawei_vrp.py
2028 lines (1764 loc) · 81.8 KB
/
huawei_vrp.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 2020 2016 Dravetech 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.
"""
NAPALM Driver for Huawei VRP5/VRP8 Routers and Switches.
Author: Locus Li (locus@byto.top)
Maintainers: Locus Li (locus@byto.top), Michael Alvarez(codingnetworks@gmail.com)
Read https://napalm.readthedocs.io for more information.
"""
import socket
import re
import telnetlib
import os
import tempfile
import paramiko
import uuid
import hashlib
import napalm.base.helpers
import napalm.base.constants as c
from datetime import datetime
from napalm.base import NetworkDriver
from napalm.base.netmiko_helpers import netmiko_args
from napalm.base.exceptions import (
MergeConfigException,
ReplaceConfigException,
CommandErrorException,
CommitError,
)
from .utils.utils import pretty_mac
# 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,4}:[0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4}:"
"[0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4}"
)
INTERFACE_REGEX = r"(?:[0-9]*GE[0-9\/\.]+)|(?:LoopBack\d+)|(?:Eth-Trunk[0-9\.]+)|(?:Vlanif[0-9\.]+)"
# 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
)
# Period needed for 32-bit AS Numbers
ASN_REGEX = r"[\d\.]+"
class VRPDriver(NetworkDriver):
"""Napalm driver for Huawei vrp."""
def __init__(self, hostname, username, password, timeout=60, optional_args=None):
"""Constructor.
:param hostname:
:param username:
:param password:
:param timeout:
:param optional_args:
"""
self.device = None
self.hostname = hostname
self.username = username
self.password = password
self.timeout = timeout
if optional_args is None:
optional_args = {}
# Netmiko possible arguments
netmiko_argument_map = {
'port': None,
'verbose': False,
'timeout': self.timeout,
'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,
'keepalive': 30
}
# Build dict of any optional Netmiko args
self.netmiko_optional_args = {
k: optional_args.get(k, v)
for k, v in netmiko_argument_map.items()
}
self.transport = optional_args.get('transport', 'ssh')
self.port = optional_args.get('port', 22)
self.changed = False
self.loaded = False
self.backup_file = ''
self.replace = False
self.merge_candidate = ''
self.replace_file = ''
self.profile = ["huawei_vrp"]
# netmiko args
self.netmiko_optional_args = netmiko_args(optional_args)
# Set the default port if not set
default_port = {"ssh": 22, "telnet": 23}
self.netmiko_optional_args.setdefault("port", default_port[self.transport])
# Control automatic execution of 'file prompt quiet' for file operations
self.auto_file_prompt = optional_args.get("auto_file_prompt", True)
# Track whether 'file prompt quiet' has been changed by NAPALM.
self.prompt_quiet_changed = False
# Track whether 'file prompt quiet' is known to be configured
self.prompt_quiet_configured = None
# verified
def open(self):
"""Open a connection to the device.
"""
device_type = "huawei"
if self.transport == "telnet":
device_type = "huawei_telnet"
self.device = self._netmiko_open(
device_type, netmiko_optional_args=self.netmiko_optional_args
)
# verified
def close(self):
"""Close the connection to the device and do the necessary cleanup."""
# Return file prompt quiet to the original state
if self.auto_file_prompt and self.prompt_quiet_changed is True:
self.device.send_config_set(["no file prompt quiet"])
self.prompt_quiet_changed = False
self.prompt_quiet_configured = False
self._netmiko_close()
# verified
def is_alive(self):
""" Returns a flag with the state of the connection."""
if self.device is None:
return {'is_alive': False}
try:
if self.transport == 'telnet':
# 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}
else:
# SSH
# Try sending ASCII null byte to maintain the connection alive
null = chr(0)
self.device.write_channel(null)
return {
'is_alive': self.device.remote_conn.transport.is_active()
}
except (socket.error, EOFError, OSError):
# If unable to send, we can tell for sure that the connection is unusable
return {'is_alive': False}
# verified
def cli(self, commands):
"""Execute a list of commands and return the output in a dictionary format using the command
Example input:
['dis version', 'dis cu']
"""
cli_output = dict()
if type(commands) is not list:
raise TypeError("Please enter a valid list of commands!")
for command in commands:
output = self.device.send_command(command)
cli_output.setdefault(command, {})
cli_output[command] = output
return cli_output
# verified
def get_facts(self):
"""Return a set of facts from the devices."""
# default values.
vendor = u'Huawei'
uptime = -1
serial_number, fqdn, os_version, hostname, model = (u'Unknown', u'Unknown', u'Unknown', u'Unknown', u'Unknown')
# obtain output from device
show_ver = self.device.send_command('display version')
show_hostname = self.device.send_command('display current-configuration | inc sysname')
show_int_status = self.device.send_command('display interface brief')
show_esn = self.device.send_command('display esn')
# os_version/uptime/model
for line in show_ver.splitlines():
if 'VRP (R) software' in line:
search_result = re.search(r"\(S\S+\s+(?P<os_version>V\S+)\)", line)
if search_result is not None:
os_version = search_result.group('os_version')
if 'HUAWEI' in line and 'uptime is' in line:
search_result = re.search(r"S\S+", line)
if search_result is not None:
model = search_result.group(0)
uptime = self._parse_uptime(line)
break
# get serial_number,due to the stack have multiple SN, so show it in a list
# 由于堆叠设备会有多少个SN,所以这里用列表展示
re_sn = r"ESN\s+of\s+slot\s+\S+\s+(?P<serial_number>\S+)"
serial_number = re.findall(re_sn, show_esn, flags=re.M)
if 'sysname ' in show_hostname:
_, hostname = show_hostname.split("sysname ")
hostname = hostname.strip()
# interface_list filter
interface_list = []
if 'Interface' in show_int_status:
_, interface_part = show_int_status.split("Interface")
re_intf = r"(?P<interface>\S+)\s+(?P<physical_state>down|up|offline|\*down)\s+" \
r"(?P<protocal_state>down|up|\*down)"
search_result = re.findall(re_intf, interface_part, flags=re.M)
for interface_info in search_result:
interface_list.append(interface_info[0])
return {
'uptime': int(uptime),
'vendor': vendor,
'os_version': os_version,
'serial_number': serial_number,
'model': model,
'hostname': hostname,
'fqdn': fqdn, # ? fqdn(fully qualified domain name)
'interface_list': interface_list
}
# developing
def get_environment(self):
"""
Return environment details.
Sample output:
{
"cpu": {
"0": {
"%usage": 18.0
}
},
"fans": {
"FAN1": {
"status": true
}
},
"memory": {
"available_ram": 3884224,
"used_ram": 784552
},
"power": {
"PWR1": {
"capacity": 600.0,
"output": 92.0,
"status": true
}
},
"temperature": {
"CPU": {
"is_alert": false,
"is_critical": false,
"temperature": 45.0
}
}
}
"""
# 空包
environment = {}
# 定义执行命令
fan_cmd = 'display fan'
"""
Slot FanID Online Status Speed Mode Airflow
-------------------------------------------------------------------------
0 1 Present Normal 55% Auto Side-to-Back
1 1 Present Normal 55% Auto Side-to-Back
"""
power_cmd = 'display power'
"""
------------------------------------------------------------
Slot PowerID Online Mode State Power(W)
------------------------------------------------------------
0 PWR1 Present AC Supply 600.00
0 PWR2 Present AC Supply 600.00
1 PWR1 Present AC Supply 600.00
1 PWR2 Present AC Supply 600.00
"""
temp_cmd = 'display temperature all'
"""
-------------------------------------------------------------------------------
Slot Card Sensor Status Current(C) Lower(C) Lower Upper(C) Upper
Resume(C) Resume(C)
-------------------------------------------------------------------------------
0 NA NA Normal 37 0 4 63 59
1 NA NA Normal 39 0 4 63 59
"""
cpu_cmd = 'display cpu-usage'
"""
CPU Usage Stat. Cycle: 60 (Second)
CPU Usage : 28% Max: 87%
CPU Usage Stat. Time : 2022-01-13 18:57:06
CPU utilization for five seconds: 28%: one minute: 28%: five minutes: 20%
Max CPU Usage Stat. Time : 2021-10-05 17:50:44.
"""
mem_cmd = 'display memory-usage'
"""
Memory utilization statistics at 2022-01-13 18:57:37+08:00
System Total Memory Is: 1598029824 bytes
Total Memory Used Is: 188593436 bytes
Memory Using Percentage Is: 11%
"""
# 发送命令
fan_output = self.device.send_command(fan_cmd)
power_cmd = self.device.send_command(power_cmd)
temp_cmd = self.device.send_command(temp_cmd)
cpu_cmd = self.device.send_command(cpu_cmd)
mem_cmd = self.device.send_command(mem_cmd)
# 设备风扇情况
environment.setdefault('fans', {})
for i in fan_output.split('\n'):
match = re.match(r"\s+(\d+).+(Normal|Abnormal).+", i)
if match:
slot = match.group(1)
status = True if match.group(2) == "Normal" else False
environment['fans'][slot] = {'status': status}
# 设备电源情况
environment.setdefault('power', {})
for i in power_cmd.split('\n'):
# match = re.match(r"\s+(\d+).+(Normal|Abnormal).+", i)
match = re.match(r"\s+(\d+)\s+(\w+\d+)\s+(\w+).+\s+(\w+)\s+(\d+\.\d+)", i)
if match:
environment['power'][f"{match.group(2)}-{match.group(1)}"] = {
"capacity": float(match.group(5)),
"output": None,
"status": True if match.group(4) == 'Supply' else False
}
# 设备温度情况
environment.setdefault('temperature', {})
for i in temp_cmd.split('\n'):
match = re.split('\s+', i)
if len(match) == 10:
if 'Upper' not in match:
environment['temperature']['slot' + match[1]] = {
"is_alert": False if match[4] == "Normal" else True,
"is_critical": False if match[4] == "Normal" else True,
"temperature": float(match[-1])
}
# CPU使用率
environment.setdefault('cpu', {})
cpu_use = re.search(r'CPU utilization for five seconds: \d+%: one minute: \d+%: five minutes: (\d+)%', cpu_cmd)
environment['cpu'] = {
"0": {
"usage": cpu_use.group(1)
}
}
# 内存使用情况
environment.setdefault('memory', {})
memory_use = re.findall(r'(\d+) bytes', mem_cmd)
environment['memory'] = {
"available_ram": int(memory_use[0]) - int(memory_use[1]),
"used_ram": int(memory_use[1])
}
return environment
# verified
def get_config(self, retrieve="all", full=False):
"""
Get config from device.
Returns the running configuration as dictionary.
The candidate and startup are always empty string for now,
since CE does not support candidate configuration.
"""
config = {
'startup': '',
'running': '',
'candidate': ''
}
if retrieve.lower() in ('running', 'all'):
command = 'display current-configuration'
config['running'] = self.device.send_command(command)
if retrieve.lower() in ('startup', 'all'):
# command = 'display saved-configuration last'
# config['startup'] = py23_compat.text_type(self.device.send_command(command))
pass
return config
# ok
def load_merge_candidate(self, filename=None, config=None):
"""Open the candidate config and merge."""
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
self.replace = False
self.loaded = True
# developing
def load_replace_candidate(self, filename=None, config=None):
"""Open the candidate config and replace."""
if not filename and not config:
raise ReplaceConfigException('filename or config param must be provided.')
self._replace_candidate(filename, config)
self.replace = True
self.loaded = True
# ok
def commit_config(self, message=""):
"""Commit configuration."""
if self.loaded:
try:
self.backup_file = 'config_' + datetime.now().strftime("%Y%m%d_%H%M") + '.cfg'
if self._check_file_exists(self.backup_file):
self._delete_file(self.backup_file)
self._save_config(self.backup_file)
if self.replace:
self._load_config(self.replace_file.split('/')[-1])
else:
self._commit_merge()
self.merge_candidate = '' # clear the merge buffer
self.changed = True
self.loaded = False
self._save_config()
except Exception as e:
raise CommitError(str(e))
else:
raise CommitError('No config loaded.')
# ok
def compare_config(self):
"""Compare candidate config with running."""
if self.loaded:
if not self.replace:
return self._get_merge_diff()
# return self.merge_candidate
diff = self._get_diff(self.replace_file.split('/')[-1])
return diff
return ''
# ok
def discard_config(self):
"""Discard changes."""
if self.loaded:
self.merge_candidate = '' # clear the buffer
if self.loaded and self.replace:
self._delete_file(self.replace_file)
self.loaded = False
# developing
def rollback(self):
"""Rollback to previous commit."""
if self.changed:
self._load_config(self.backup_file)
self.changed = False
self._save_config()
# verified
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."""
ping_dict = {}
command = 'ping'
# Timeout in milliseconds to wait for each reply, the default is 2000
command += ' -t {}'.format(timeout * 1000)
# Specify the number of data bytes to be sent
command += ' -s {}'.format(size)
# Specify the number of echo requests to be sent
command += ' -c {}'.format(count)
if source != '':
command += ' -a {}'.format(source)
command += ' {}'.format(destination)
output = self.device.send_command(command)
if 'Error' 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': []
}
match_sent = re.search(r"(\d+).+transmitted", output, re.M)
match_received = re.search(r"(\d+).+received", output, re.M)
try:
probes_sent = int(match_sent.group(1))
probes_received = int(match_received.group(1))
ping_dict['success']['probes_sent'] = probes_sent
ping_dict['success']['packet_loss'] = probes_sent - probes_received
except Exception:
msg = "Unexpected output data:\n{}".format(output)
raise ValueError(msg)
match = re.search(r"min/avg/max = (\d+)/(\d+)/(\d+)", output, re.M)
if match:
ping_dict['success'].update({
'rtt_min': float(match.group(1)),
'rtt_avg': float(match.group(2)),
'rtt_max': float(match.group(3)),
})
results_array = []
match = re.findall(r"Reply from.+time=(\d+)", output, re.M)
for i in match:
results_array.append({'ip_address': destination,
'rtt': float(i)})
ping_dict['success'].update({'results': results_array})
return ping_dict
# developing
def traceroute(self):
pass
# get information from network device
# verified
def get_interfaces(self):
"""
Get interface details (last_flapped is not implemented).
Sample Output:
{
"Vlanif3000": {
"is_enabled": false,
"description": "Route Port,The Maximum Transmit Unit is 1500",
"last_flapped": -1.0,
"is_up": false,
"mac_address": "0C:45:BA:7D:83:E6",
"speed": -1
},
"Vlanif100": {
"is_enabled": false,
"description": "Route Port,The Maximum Transmit Unit is 1500",
"last_flapped": -1.0,
"is_up": false,
"mac_address": "0C:45:BA:7D:83:E4",
"speed": -1
}
}
"""
interfaces = {}
output = self.device.send_command('display interface')
if not output:
return {}
separator = r"(^(?!Line protocol).*current state.*$)"
re_intf_name_state = r"^(?!Line protocol)(?P<intf_name>\S+).+current state\W+(?P<intf_state>.+)$"
re_protocol = r"Line protocol current state\W+(?P<protocol>.+)$"
re_mac = r"Hardware address is\W+(?P<mac_address>\S+)"
re_speed = r"^Speed\W+(?P<speed>\d+|\w+)"
re_description = r"^Description\W+(?P<description>.*)$"
new_interfaces = self._separate_section(separator, output)
for interface in new_interfaces:
interface = interface.strip()
match_intf = re.search(re_intf_name_state, interface, flags=re.M)
match_proto = re.search(re_protocol, interface, flags=re.M)
if match_intf is None or match_proto is None:
msg = "Unexpected interface format: {}".format(interface)
raise ValueError(msg)
intf_name = match_intf.group('intf_name')
intf_state = match_intf.group('intf_state')
is_enabled = bool('up' in intf_state.lower())
protocol = match_proto.group('protocol')
is_up = bool('up' in protocol.lower())
match_mac = re.search(re_mac, interface, flags=re.M)
if match_mac:
mac_address = match_mac.group('mac_address')
mac_address = napalm.base.helpers.mac(mac_address)
else:
mac_address = ""
speed = -1
match_speed = re.search(re_speed, interface, flags=re.M)
if match_speed:
speed = match_speed.group('speed')
if speed.isdigit():
speed = int(speed)
description = ''
match = re.search(re_description, interface, flags=re.M)
if match:
description = match.group('description')
interfaces.update({
intf_name: {
'description': description,
'is_enabled': is_enabled,
'is_up': is_up,
'last_flapped': -1.0,
'mac_address': mac_address,
'speed': speed}
})
return interfaces
# verified
def get_interfaces_ip(self):
"""
Get interface IP details. Returns a dictionary of dictionaries.
Sample output:
{
"LoopBack0": {
"ipv4": {
"192.168.0.9": {
"prefix_length": 32
}
}
},
"Vlanif2000": {
"ipv4": {
"192.168.200.3": {
"prefix_length": 24
},
"192.168.200.6": {
"prefix_length": 24
},
"192.168.200.8": {
"prefix_length": 24
}
},
"ipv6": {
"FC00::1": {
"prefix_length": 64
}
}
}
}
"""
interfaces_ip = {}
output_v4 = self.device.send_command('display ip interface')
output_v6 = self.device.send_command('display ipv6 interface')
v4_interfaces = {}
separator = r"(^(?!Line protocol).*current state.*$)"
new_v4_interfaces = self._separate_section(separator, output_v4)
for interface in new_v4_interfaces:
re_intf_name_state = r"^(?!Line protocol)(?P<intf_name>\S+).+current state\W+(?P<intf_state>.+)$"
re_intf_ip = r"Internet Address is\s+(?P<ip_address>\d+.\d+.\d+.\d+)\/(?P<prefix_length>\d+)"
match_intf = re.search(re_intf_name_state, interface, flags=re.M)
if match_intf is None:
msg = "Unexpected interface format: {}".format(interface)
raise ValueError(msg)
intf_name = match_intf.group('intf_name')
# v4_interfaces[intf_name] = {}
match_ip = re.findall(re_intf_ip, interface, flags=re.M)
for ip_info in match_ip:
val = {'prefix_length': int(ip_info[1])}
# v4_interfaces[intf_name][ip_info[0]] = val
v4_interfaces.setdefault(intf_name, {})[ip_info[0]] = val
v6_interfaces = {}
separator = r"(^(?!IPv6 protocol).*current state.*$)"
new_v6_interfaces = self._separate_section(separator, output_v6)
for interface in new_v6_interfaces:
re_intf_name_state = r"^(?!IPv6 protocol)(?P<intf_name>\S+).+current state\W+(?P<intf_state>.+)$"
re_intf_ip = r"(?P<ip_address>\S+), subnet is.+\/(?P<prefix_length>\d+)"
match_intf = re.search(re_intf_name_state, interface, flags=re.M)
if match_intf is None:
msg = "Unexpected interface format: {}".format(interface)
raise ValueError(msg)
intf_name = match_intf.group('intf_name')
match_ip = re.findall(re_intf_ip, interface, flags=re.M)
for ip_info in match_ip:
val = {'prefix_length': int(ip_info[1])}
v6_interfaces.setdefault(intf_name, {})[ip_info[0]] = val
# Join data from intermediate dictionaries.
for interface, data in v4_interfaces.items():
interfaces_ip.setdefault(interface, {'ipv4': {}})['ipv4'] = data
for interface, data in v6_interfaces.items():
interfaces_ip.setdefault(interface, {'ipv6': {}})['ipv6'] = data
return interfaces_ip
# verified
def get_interfaces_counters(self):
"""Return interfaces counters."""
def process_counts(tup):
for item in tup:
if item != "":
return int(item)
return 0
interfaces = {}
# command "display interface counters" lacks of some keys
output = self.device.send_command('display interface')
if not output:
return {}
separator = r"(^(?!Line protocol).*current state.*$)"
re_intf_name_state = r"^(?!Line protocol)(?P<intf_name>\S+).+current state\W+(?P<intf_state>.+)$"
re_unicast = r"Unicast:\s+(\d+)|(\d+)\s+unicast"
re_multicast = r"Multicast:\s+(\d+)|(\d+)\s+multicast"
re_broadcast = r"Broadcast:\s+(\d+)|(\d+)\s+broadcast"
re_dicards = r"Discard:\s+(\d+)|(\d+)\s+discard"
re_rx_octets = r"Input.+\s+(\d+)\sbytes|Input:.+,(\d+)\sbytes"
re_tx_octets = r"Output.+\s+(\d+)\sbytes|Output:.+,(\d+)\sbytes"
re_errors = r"Total Error:\s+(\d+)|(\d+)\s+errors"
new_interfaces = self._separate_section(separator, output)
for interface in new_interfaces:
interface = interface.strip()
match_intf = re.search(re_intf_name_state, interface, flags=re.M)
if match_intf is None:
msg = "Unexpected interface format: {}".format(interface)
raise ValueError(msg)
intf_name = match_intf.group('intf_name')
intf_counter = {
'tx_errors': 0,
'rx_errors': 0,
'tx_discards': 0,
'rx_discards': 0,
'tx_octets': 0,
'rx_octets': 0,
'tx_unicast_packets': 0,
'rx_unicast_packets': 0,
'tx_multicast_packets': 0,
'rx_multicast_packets': 0,
'tx_broadcast_packets': 0,
'rx_broadcast_packets': 0
}
match = re.findall(re_errors, interface, flags=re.M)
if match:
intf_counter['rx_errors'] = process_counts(match[0])
if len(match) == 2:
intf_counter['tx_errors'] = process_counts(match[1])
match = re.findall(re_dicards, interface, flags=re.M)
if len(match) == 2:
intf_counter['rx_discards'] = process_counts(match[0])
intf_counter['tx_discards'] = process_counts(match[1])
match = re.findall(re_unicast, interface, flags=re.M)
if len(match) == 2:
intf_counter['rx_unicast_packets'] = process_counts(match[0])
intf_counter['tx_unicast_packets'] = process_counts(match[1])
match = re.findall(re_multicast, interface, flags=re.M)
if len(match) == 2:
intf_counter['rx_multicast_packets'] = process_counts(match[0])
intf_counter['tx_multicast_packets'] = process_counts(match[1])
match = re.findall(re_broadcast, interface, flags=re.M)
if len(match) == 2:
intf_counter['rx_broadcast_packets'] = process_counts(match[0])
intf_counter['tx_broadcast_packets'] = process_counts(match[1])
match = re.findall(re_rx_octets, interface, flags=re.M)
if match:
intf_counter['rx_octets'] = process_counts(match[0])
match = re.findall(re_tx_octets, interface, flags=re.M)
if match:
intf_counter['tx_octets'] = process_counts(match[0])
interfaces.update({
intf_name: intf_counter
})
return interfaces
# verified
def get_lldp_neighbors(self):
"""
Return LLDP neighbors brief info.
Sample input:
<device-vrp>dis lldp neighbor brief
Local Intf Neighbor Dev Neighbor Intf Exptime(s)
XGE0/0/1 huawei-S5720-01 XGE0/0/1 96
XGE0/0/3 huawei-S5720-POE XGE0/0/1 119
XGE0/0/46 Aruba-7210-M GE0/0/2 95
Sample output:
{
'XGE0/0/1': [
{
'hostname': 'huawei-S5720-01',
'port': 'XGE0/0/1'
},
'XGE0/0/3': [
{
'hostname': 'huawei-S5720-POE',
'port': 'XGE0/0/1'
},
'XGE0/0/46': [
{
'hostname': 'Aruba-7210-M',
'port': 'GE0/0/2'
},
]
}
"""
results = {}
command = 'display lldp neighbor brief'
output = self.device.send_command(command)
re_lldp = r"(?P<local>\S+)\s+(?P<hostname>\S+)\s+(?P<port>\S+)\s+\d+\s+"
match = re.findall(re_lldp, output, re.M)
for neighbor in match:
local_intf = neighbor[0]
if local_intf not in results:
results[local_intf] = []
neighbor_dict = dict()
neighbor_dict['hostname'] = neighbor[1]
neighbor_dict['port'] = neighbor[2]
results[local_intf].append(neighbor_dict)
return results
# develop
def get_lldp_neighbors_detail(self, interface=""):
pass
"""
Return a detailed view of the LLDP neighbors as a dictionary.
Sample output:
{
}
"""
lldp_neighbors = {}
return lldp_neighbors
# verified
def get_arp_table(self, vrf=""):
"""
Get arp table information.
Return a list of dictionaries having the following set of keys:
* interface (string)
* mac (string)
* ip (string)
* age (float) (not support)
Sample output:
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : -1
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : -1
}
]
"""
arp_table = []
output = self.device.send_command('display arp')
re_arp = r"(?P<ip_address>\d+\.\d+\.\d+\.\d+)\s+(?P<mac>\S+)\s+(?P<exp>\d+|)\s+" \
r"(?P<type>I|D|S|O)\S+\s+(?P<interface>\S+)"
match = re.findall(re_arp, output, flags=re.M)
for arp in match:
# if arp[2].isdigit():
# exp = float(arp[2]) * 60
# else:
# exp = 0
entry = {
'interface': arp[4],
'mac': pretty_mac(arp[1]),
'ip': arp[0],
'age': -1.0,
}
arp_table.append(entry)
return arp_table
# verified
def get_mac_address_table(self):
"""
Return the MAC address table.
Sample output:
[
{
"active": true,
"interface": "10GE1/0/1",
"last_move": -1.0,
"mac": "00:00:00:00:00:33",
"moves": -1,
"static": false,
"vlan": 100
},
{
"active": false,
"interface": "10GE1/0/2",
"last_move": -1.0,
"mac": "00:00:00:00:00:01",
"moves": -1,
"static": true,
"vlan": 200
}
]
MAC type:
标识MAC地址的类型:
static: 静态MAC地址表项。由用户手工配置,表项不会被老化。
blackhole: 标识黑洞MAC地址表项,由用户手工配置,表项不会被老化。可以通过命令mac-address blackhole配置。
dynamic: 标识动态MAC地址表项,由设备通过源MAC地址学习获得,表项有老化时间,可被老化。
security: 标识安全动态MAC表项,由接口使能端口安全功能后学习到的MAC地址表项。
sec-config: 标识安全静态MAC表项,由命令port-security mac-address配置的MAC地址表项。
sticky: 标识Sticky MAC表项,由接口使能Sticky MAC功能后学习到的MAC地址表项。
mux: 标识MUX MAC表项,当接口使能MUX VLAN功能后,该接口学习到的MAC地址表项会记录到mux类型的MAC地址表项中。
snooping: 根据DHCP Snooping绑定表生成的静态MAC表项类型。
authen: 已获取到IP地址的NAC认证用户(无法生成MAC地址的三层Portal认证用户和直接转发模式下的无线用户除外)对应的MAC地址表项。
pre-authen: 用户使能NAC认证功能后,处于预连接状态且未获取到IP地址的NAC认证用户对应的MAC地址表项。
evpn: 标识EVPN网络中存在的MAC地址表项。
"""
mac_address_table = []
command = 'display mac-address'
output = self.device.send_command(command)
re_mac = r"(?P<mac>\S+)\s+(?P<vlan>\d+|-)\S+\s+(?P<interface>\S+)\s+(?P<type>\w+)\s+"
match = re.findall(re_mac, output, re.M)
for mac_info in match:
mac_dict = {
'mac': napalm.base.helpers.mac(mac_info[0]),
'interface': mac_info[2],
'vlan': int(mac_info[1]),
'static': True if mac_info[3] == "static" else False,
'active': True if mac_info[3] == "dynamic" else False,
'authen': True if mac_info[3] == "authen" else False,
'moves': -1,
'last_move': -1.0
}
mac_address_table.append(mac_dict)
return mac_address_table
# developing
def get_probes_config(self):
pass
# developing
def get_probes_results(self):
pass
# verified
def get_bgp_neighbors(self):
"""
{