Merge branch 'develop' into interface_counters

This commit is contained in:
Petr Klima committed 2021-03-08 15:33:16 +01:00
commit bfe83c9c0c
17 files changed
+212 -219

No files matched your search

+3 -1
View File
@@ -23,6 +23,8 @@ pip3 install napalm_s350
Default information (the same as `call get_facts`) Default information (the same as `call get_facts`)
```bash ```bash
napalm --user USER --password PASSWORD --vendor s350 HOSTNAME napalm --user USER --password PASSWORD --vendor s350 HOSTNAME
napalm --user USER --password PASSWORD --vendor s350 HOSTNAME --optional_args "force_no_enable=True"
``` ```
Get interfaces Get interfaces
@@ -48,7 +50,7 @@ be supported.
| function | SG300 | SG500 | SG350 | SG550 | stack SG500 | stack SG550 | | function | SG300 | SG500 | SG350 | SG550 | stack SG500 | stack SG550 |
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | | :--- | :---: | :---: | :---: | :---: | :---: | :---: |
| **Send commands** | | **Send commands** |
| cli | | | | | | | | cli | x | x | x | x | x | x |
| **Config manipulation** | | **Config manipulation** |
|get_config | x | x | x | x | | | |get_config | x | x | x | x | | |
|get_config (filtered) | x | x | x | x | | | |get_config (filtered) | x | x | x | x | | |
+1 -1
View File
@@ -15,4 +15,4 @@
"""napalm-s350 package.""" """napalm-s350 package."""
from napalm_s350.s350 import S350Driver # noqa from napalm_s350.s350 import S350Driver # noqa
__all__ = ('S350Driver',) __all__ = ("S350Driver",)
+197 -196
View File
@@ -40,9 +40,9 @@ import napalm.base.canonical_map
# make may own base_interfaces for s350 # make may own base_interfaces for s350
s350_base_interfaces = { s350_base_interfaces = {
**napalm.base.canonical_map.base_interfaces, **napalm.base.canonical_map.base_interfaces,
'fa': 'FastEthernet', "fa": "FastEthernet",
'gi': 'GigabitEthernet', "gi": "GigabitEthernet",
'te': 'TengigabitEthernet' "te": "TengigabitEthernet",
} }
@@ -60,23 +60,23 @@ class S350Driver(NetworkDriver):
if optional_args is None: if optional_args is None:
optional_args = {} optional_args = {}
self._dest_file_system = optional_args.get('dest_file_system', None) self._dest_file_system = optional_args.get("dest_file_system", None)
# Netmiko possible arguments # Netmiko possible arguments
netmiko_argument_map = { netmiko_argument_map = {
'port': None, "port": None,
'secret': '', "secret": "",
'verbose': False, "verbose": False,
'keepalive': 30, "keepalive": 30,
'global_delay_factor': 1, "global_delay_factor": 1,
'use_keys': False, "use_keys": False,
'key_file': None, "key_file": None,
'ssh_strict': False, "ssh_strict": False,
'system_host_keys': False, "system_host_keys": False,
'alt_host_keys': False, "alt_host_keys": False,
'alt_key_file': '', "alt_key_file": "",
'ssh_config_file': None, "ssh_config_file": None,
'allow_agent': False, "allow_agent": False,
} }
# Allow for passing additional Netmiko arguments # Allow for passing additional Netmiko arguments
@@ -87,30 +87,47 @@ class S350Driver(NetworkDriver):
except KeyError: except KeyError:
pass pass
self.port = optional_args.get('port', 22) self.port = optional_args.get("port", 22)
self.device = None self.device = None
self.force_no_enable = optional_args.get("force_no_enable", False)
def open(self): def open(self):
"""Open a connection to the device.""" """Open a connection to the device."""
self.device = ConnectHandler(device_type='cisco_s300',
self.device = ConnectHandler(
device_type="cisco_s300",
host=self.hostname, host=self.hostname,
username=self.username, username=self.username,
password=self.password, password=self.password,
**self.netmiko_optional_args) **self.netmiko_optional_args,
)
if not self.force_no_enable:
self.device.enable() self.device.enable()
def _discover_file_system(self): def _discover_file_system(self):
try: try:
return self.device._autodetect_fs() return self.device._autodetect_fs()
except Exception: except Exception:
msg = "Netmiko _autodetect_fs failed (to work around specify " \ msg = (
"Netmiko _autodetect_fs failed (to work around specify "
"dest_file_system in optional_args)." "dest_file_system in optional_args)."
)
raise CommandErrorException(msg) raise CommandErrorException(msg)
def close(self): def close(self):
"""Close the connection to the device.""" """Close the connection to the device."""
self.device.disconnect() self.device.disconnect()
def cli(self, commands):
output = {}
try:
for cmd in commands:
output[cmd] = self.device.send_command(cmd)
return output
except (socket.error, EOFError) as e:
raise ConnectionClosedException(str(e))
def _send_command(self, command): def _send_command(self, command):
"""Wrapper for self.device.send.command(). """Wrapper for self.device.send.command().
@@ -131,9 +148,9 @@ class S350Driver(NetworkDriver):
def _parse_uptime(self, uptime_str): def _parse_uptime(self, uptime_str):
"""Parse an uptime string into number of seconds""" """Parse an uptime string into number of seconds"""
uptime_str = uptime_str.strip() uptime_str = uptime_str.strip()
days, timespec = uptime_str.split(',') days, timespec = uptime_str.split(",")
hours, minutes, seconds = timespec.split(':') hours, minutes, seconds = timespec.split(":")
uptime_sec = (int(days) * 86400) + (int(hours) * 3600) + (int(minutes) * 60) + int(seconds) uptime_sec = (int(days) * 86400) + (int(hours) * 3600) + (int(minutes) * 60) + int(seconds)
return uptime_sec return uptime_sec
@@ -147,11 +164,11 @@ class S350Driver(NetworkDriver):
arp_table = [] arp_table = []
output = self._send_command('show arp') output = self._send_command("show arp")
for line in output.splitlines(): for line in output.splitlines():
# A VLAN may not be set for the entry # A VLAN may not be set for the entry
if 'vlan' not in line: if "vlan" not in line:
continue continue
if len(line.split()) == 4: if len(line.split()) == 4:
interface, ip, mac, _ = line.split() interface, ip, mac, _ = line.split()
@@ -161,45 +178,42 @@ class S350Driver(NetworkDriver):
elif len(line.split()) == 6: elif len(line.split()) == 6:
_, _, interface, ip, mac, _ = line.split() _, _, interface, ip, mac, _ = line.split()
else: else:
raise ValueError('Unexpected output: {}'.format(line.split())) raise ValueError("Unexpected output: {}".format(line.split()))
interface = canonical_interface_name( interface = canonical_interface_name(interface, s350_base_interfaces)
interface,
s350_base_interfaces
)
entry = { entry = {
'interface': interface, "interface": interface,
'mac': napalm.base.helpers.mac(mac), "mac": napalm.base.helpers.mac(mac),
'ip': ip, "ip": ip,
'age': 0.0, "age": 0.0,
} }
arp_table.append(entry) arp_table.append(entry)
return arp_table return arp_table
def get_config(self, retrieve='all', full=False, sanitized=False): def get_config(self, retrieve="all", full=False, sanitized=False):
""" """
get_config for S350. Since this firmware doesn't support a candidate get_config for S350. Since this firmware doesn't support a candidate
configuration we leave it empty. configuration we leave it empty.
""" """
configs = { configs = {
'startup': '', "startup": "",
'running': '', "running": "",
'candidate': '', "candidate": "",
} }
if retrieve in ('all', 'startup'): if retrieve in ("all", "startup"):
startup = self._send_command('show startup-config') startup = self._send_command("show startup-config")
configs['startup'] = self._get_config_filter(startup) configs["startup"] = self._get_config_filter(startup)
if retrieve in ('all', 'running'): if retrieve in ("all", "running"):
# IOS supports "full" only on "show running-config" # IOS supports "full" only on "show running-config"
run_full = " detailed" if full else "" run_full = " detailed" if full else ""
running = self._send_command('show running-config' + run_full) running = self._send_command("show running-config" + run_full)
configs['running'] = self._get_config_filter(running) configs["running"] = self._get_config_filter(running)
if sanitized: if sanitized:
configs = self._get_config_sanitized(configs) configs = self._get_config_sanitized(configs)
@@ -237,23 +251,23 @@ class S350Driver(NetworkDriver):
def get_facts(self): def get_facts(self):
"""Return a set of facts from the device.""" """Return a set of facts from the device."""
serial_number, fqdn, os_version, hostname, domainname = ('Unknown',) * 5 serial_number, fqdn, os_version, hostname, domainname = ("Unknown",) * 5
# Submit commands to the device. # Submit commands to the device.
show_ver = self._send_command('show version') show_ver = self._send_command("show version")
show_sys = self._send_command('show system') show_sys = self._send_command("show system")
show_inv = self._send_command('show inventory') show_inv = self._send_command("show inventory")
show_hosts = self._send_command('show hosts') show_hosts = self._send_command("show hosts")
show_int_st = self._send_command('show interface status') show_int_st = self._send_command("show interfaces status")
os_version = self._get_facts_parse_os_version(show_ver) os_version = self._get_facts_parse_os_version(show_ver)
# hostname # hostname
hostname = self._get_facts_hostname(show_sys) hostname = self._get_facts_hostname(show_sys)
# special case for SG500 fw v1.4.x # special case for SG500 fw v1.4.x
if hostname == 'Unknown': if hostname == "Unknown":
hostname = self._get_facts_hostname_from_config( hostname = self._get_facts_hostname_from_config(
self._send_command('show running-config') self._send_command("show running-config")
) )
# uptime # uptime
@@ -261,65 +275,60 @@ class S350Driver(NetworkDriver):
uptime = self._parse_uptime(uptime_str) uptime = self._parse_uptime(uptime_str)
# serial_number and model # serial_number and model
inventory = self._get_facts_parse_inventory(show_inv)['1'] inventory = self._get_facts_parse_inventory(show_inv)["1"]
serial_number = inventory['sn'] serial_number = inventory["sn"]
model = inventory['pid'] model = inventory["pid"]
# fqdn # fqdn
domainname = napalm.base.helpers.textfsm_extractor(self, 'hosts', domainname = napalm.base.helpers.textfsm_extractor(self, "hosts", show_hosts)[0]
show_hosts)[0] domainname = domainname["domain_name"]
domainname = domainname['domain_name'] if domainname == "Domain":
if domainname == 'Domain': domainname = "Unknown"
domainname = 'Unknown'
if domainname != "Unknown" and hostname != "Unknown": if domainname != "Unknown" and hostname != "Unknown":
fqdn = '{0}.{1}'.format(hostname, domainname) fqdn = "{0}.{1}".format(hostname, domainname)
# interface_list # interface_list
interfaces = [] interfaces = []
show_int_st = show_int_st.strip() show_int_st = show_int_st.strip()
# remove the header information # remove the header information
show_int_st = re.sub( show_int_st = re.sub(
r"(^-.*$|^Port .*$|^Ch .*$)|^\s.*$|^.*Flow.*$", "", show_int_st, r"(^-.*$|^Port .*$|^Ch .*$)|^\s.*$|^.*Flow.*$", "", show_int_st, flags=re.M
flags=re.M
) )
for line in show_int_st.splitlines(): for line in show_int_st.splitlines():
if not line: if not line:
continue continue
interface = line.split()[0] interface = line.split()[0]
interface = canonical_interface_name( interface = canonical_interface_name(interface, s350_base_interfaces)
interface,
s350_base_interfaces
)
interfaces.append(str(interface)) interfaces.append(str(interface))
return { return {
'fqdn': str(fqdn), "fqdn": str(fqdn),
'hostname': str(hostname), "hostname": str(hostname),
'interface_list': interfaces, "interface_list": interfaces,
'model': str(model), "model": str(model),
'os_version': str(os_version), "os_version": str(os_version),
'serial_number': str(serial_number), "serial_number": str(serial_number),
'uptime': uptime, "uptime": uptime,
'vendor': u'Cisco', "vendor": "Cisco",
} }
def _get_facts_hostname_from_config(self, show_running): def _get_facts_hostname_from_config(self, show_running):
# special case for SG500 fw v1.4.x # special case for SG500 fw v1.4.x
hostname = 'Unknown' hostname = "Unknown"
for line in show_running.splitlines(): for line in show_running.splitlines():
if line.startswith('hostname '): if line.startswith("hostname "):
_, hostname = line.split('hostname') _, hostname = line.split("hostname")
hostname = hostname.strip() hostname = hostname.strip()
break break
return hostname return hostname
def _get_facts_hostname(self, show_sys): def _get_facts_hostname(self, show_sys):
hostname = 'Unknown' hostname = "Unknown"
for line in show_sys.splitlines(): for line in show_sys.splitlines():
if line.startswith('System Name:'): if line.startswith("System Name:"):
_, hostname = line.split('System Name:') _, hostname = line.split("System Name:")
hostname = hostname.strip() hostname = hostname.strip()
break break
@@ -333,17 +342,17 @@ class S350Driver(NetworkDriver):
uptime_str = None uptime_str = None
for line in show_sys.splitlines(): for line in show_sys.splitlines():
# All models except SG500 fw 1.4.x # All models except SG500 fw 1.4.x
if line.startswith('System Up Time (days,hour:min:sec):'): if line.startswith("System Up Time (days,hour:min:sec):"):
_, uptime_str = line.split('System Up Time (days,hour:min:sec):') _, uptime_str = line.split("System Up Time (days,hour:min:sec):")
break break
line = re.sub(r' *', ' ', line, re.M) line = re.sub(r" *", " ", line, re.M)
line = line.strip() line = line.strip()
fields = line.split(' ') fields = line.split(" ")
syslines.append(fields) syslines.append(fields)
if 'Unit' in syslines[i] and 'time' in syslines[i]: if "Unit" in syslines[i] and "time" in syslines[i]:
uptime_header_lineNo = i uptime_header_lineNo = i
i += 1 i += 1
@@ -357,25 +366,29 @@ class S350Driver(NetworkDriver):
def _get_facts_parse_inventory(self, show_inventory): def _get_facts_parse_inventory(self, show_inventory):
""" inventory can list more modules/devices """ """ inventory can list more modules/devices """
# make 1 module 1 line # make 1 module 1 line
show_inventory = re.sub(r'\nPID', ' PID', show_inventory, re.M) show_inventory = re.sub(r"\nPID", " PID", show_inventory, re.M)
# delete empty lines # delete empty lines
show_inventory = re.sub(r'^\n', '', show_inventory, re.M) show_inventory = re.sub(r"^\n", "", show_inventory, re.M)
show_inventory = re.sub(r'\n\n', '', show_inventory, re.M) show_inventory = re.sub(r"\n\n", "", show_inventory, re.M)
show_inventory = re.sub(r'\n\s*\n', r'\n', show_inventory, re.M) show_inventory = re.sub(r"\n\s*\n", r"\n", show_inventory, re.M)
lines = show_inventory.splitlines() lines = show_inventory.splitlines()
modules = {} modules = {}
for line in lines: for line in lines:
match = re.search(r""" match = re.search(
r"""
^ ^
NAME:\s"(?P<name>\S+)"\s* NAME:\s"(?P<name>\S+)"\s*
DESCR:\s"(?P<descr>[^"]+)"\s* DESCR:\s"(?P<descr>[^"]+)"\s*
PID:\s(?P<pid>\S+)\s* PID:\s(?P<pid>\S+)\s*
VID:\s(?P<vid>.+\S)\s* VID:\s(?P<vid>.+\S)\s*
SN:\s(?P<sn>\S+)\s* SN:\s(?P<sn>\S+)\s*
""", line, re.X) """,
line,
re.X,
)
module = match.groupdict() module = match.groupdict()
modules[module['name']] = module modules[module["name"]] = module
if modules: if modules:
return modules return modules
@@ -387,21 +400,21 @@ class S350Driver(NetworkDriver):
for line in show_ver.splitlines(): for line in show_ver.splitlines():
# First version line is the active version # First version line is the active version
if re.search(r"Version:", line): if re.search(r"Version:", line):
_, os_version = line.split('Version: ') _, os_version = line.split("Version: ")
break break
elif re.search(r"^SW version", show_ver): elif re.search(r"^SW version", show_ver):
for line in show_ver.splitlines(): for line in show_ver.splitlines():
if re.search(r"^SW version", line): if re.search(r"^SW version", line):
_, ver = line.split(' ') _, ver = line.split(" ")
os_version, _ = ver.split(' (') os_version, _ = ver.split(" (")
break break
else: else:
# show_ver = re.sub(r'^\n', '', show_ver, re.M) # show_ver = re.sub(r'^\n', '', show_ver, re.M)
for line in show_ver.splitlines(): for line in show_ver.splitlines():
line = re.sub(r' *', ' ', line, re.M) line = re.sub(r" *", " ", line, re.M)
line = line.strip() line = line.strip()
line_comps = line.split(' ') line_comps = line.split(" ")
if line_comps[0] == '1': if line_comps[0] == "1":
os_version = line_comps[1] os_version = line_comps[1]
break break
@@ -413,21 +426,21 @@ class S350Driver(NetworkDriver):
""" """
interfaces = {} interfaces = {}
show_status_output = self._send_command('show interfaces status') show_status_output = self._send_command("show interfaces status")
show_description_output = self._send_command('show interfaces description') show_description_output = self._send_command("show interfaces description")
# by documentation SG350 # by documentation SG350
show_jumbo_frame = self._send_command('show ports jumbo-frame') show_jumbo_frame = self._send_command("show ports jumbo-frame")
match = re.search(r'Jumbo frames are enabled', show_jumbo_frame, re.M) match = re.search(r"Jumbo frames are enabled", show_jumbo_frame, re.M)
if match: if match:
mtu = 9000 mtu = 9000
else: else:
mtu = 1518 mtu = 1518
mac = '0' mac = "0"
for status_line in show_status_output.splitlines(): for status_line in show_status_output.splitlines():
if 'Up' in status_line or 'Down' in status_line: if "Up" in status_line or "Down" in status_line:
if "Po" in status_line: if "Po" in status_line:
interface, _, _, speed, _, _, link_state = status_line.split() interface, _, _, speed, _, _, link_state = status_line.split()
else: else:
@@ -435,40 +448,37 @@ class S350Driver(NetworkDriver):
# Since the MAC address for all the local ports are equal, get the address # Since the MAC address for all the local ports are equal, get the address
# from the first port and use it everywhere. # from the first port and use it everywhere.
if mac == '0': if mac == "0":
show_system_output = self._send_command('show lldp local ' + interface) show_system_output = self._send_command("show lldp local " + interface)
mac = show_system_output.splitlines()[0].split(':', maxsplit=1)[1].strip() mac = show_system_output.splitlines()[0].split(":", maxsplit=1)[1].strip()
if speed == '--': if speed == "--":
is_enabled = False is_enabled = False
speed = 0 speed = 0
else: else:
is_enabled = True is_enabled = True
speed = int(speed) speed = int(speed)
is_up = (link_state == 'Up') is_up = link_state == "Up"
for descr_line in show_description_output.splitlines(): for descr_line in show_description_output.splitlines():
description = 0 description = 0
if descr_line.startswith(interface): if descr_line.startswith(interface):
description = ' '.join(descr_line.split()[1:]) description = " ".join(descr_line.split()[1:])
break break
# last_flapped can not be get - setting to default # last_flapped can not be get - setting to default
entry = { entry = {
'is_up': is_up, "is_up": is_up,
'is_enabled': is_enabled, "is_enabled": is_enabled,
'speed': speed, "speed": speed,
'mtu': mtu, "mtu": mtu,
'last_flapped': -1.0, "last_flapped": -1.0,
'description': description, "description": description,
'mac_address': napalm.base.helpers.mac(mac) "mac_address": napalm.base.helpers.mac(mac),
} }
interface = canonical_interface_name( interface = canonical_interface_name(interface, s350_base_interfaces)
interface,
s350_base_interfaces
)
interfaces[interface] = entry interfaces[interface] = entry
@@ -477,47 +487,38 @@ class S350Driver(NetworkDriver):
def get_interfaces_ip(self): def get_interfaces_ip(self):
"""Returns all configured interface IP addresses.""" """Returns all configured interface IP addresses."""
interfaces = {} interfaces = {}
show_ip_int = self._send_command('show ip int') show_ip_int = self._send_command("show ip int")
header = True # cycle trought header header = True # cycle trought header
for line in show_ip_int.splitlines(): for line in show_ip_int.splitlines():
if header: if header:
# last line of first header # last line of first header
match = re.match(r'^---+ -+ .*$', line) match = re.match(r"^---+ -+ .*$", line)
if match: if match:
header = False header = False
fields_end = self._get_ip_int_fields_end(line) fields_end = self._get_ip_int_fields_end(line)
continue continue
# next header, stop processing text # next header, stop processing text
if re.match(r'^---+ -+ .*$', line): if re.match(r"^---+ -+ .*$", line):
break break
line_elems = self._get_ip_int_line_to_fields(line, fields_end) line_elems = self._get_ip_int_line_to_fields(line, fields_end)
# only valid interfaces # only valid interfaces
# in diferent firmwares there is 'Status' field allwais on last place # in diferent firmwares there is 'Status' field allwais on last place
if line_elems[len(line_elems) - 1] != 'Valid': if line_elems[len(line_elems) - 1] != "Valid":
continue continue
cidr = line_elems[0] cidr = line_elems[0]
interface = line_elems[1] interface = line_elems[1]
ip = netaddr.IPNetwork(cidr) ip = netaddr.IPNetwork(cidr)
family = 'ipv{0}'.format(ip.version) family = "ipv{0}".format(ip.version)
interface = canonical_interface_name( interface = canonical_interface_name(interface, s350_base_interfaces)
interface,
s350_base_interfaces
)
interfaces[interface] = { interfaces[interface] = {family: {str(ip.ip): {"prefix_length": ip.prefixlen}}}
family: {
str(ip.ip): {
'prefix_length': ip.prefixlen
}
}
}
return interfaces return interfaces
@@ -535,7 +536,7 @@ class S350Driver(NetworkDriver):
def _get_ip_int_fields_end(self, dashline): def _get_ip_int_fields_end(self, dashline):
""" fields length are diferent device to device, detect them on horizontal lin """ """ fields length are diferent device to device, detect them on horizontal lin """
fields_end = [m.start() for m in re.finditer(' ', dashline.strip())] fields_end = [m.start() for m in re.finditer(" ", dashline.strip())]
# fields_position.insert(0,0) # fields_position.insert(0,0)
fields_end.append(len(dashline)) fields_end.append(len(dashline))
@@ -544,16 +545,16 @@ class S350Driver(NetworkDriver):
def get_lldp_neighbors(self): def get_lldp_neighbors(self):
"""get_lldp_neighbors implementation for s350""" """get_lldp_neighbors implementation for s350"""
neighbors = {} neighbors = {}
output = self._send_command('show lldp neighbors') output = self._send_command("show lldp neighbors")
header = True # cycle trought header header = True # cycle trought header
local_port = '' # keep previous context - multiline syname local_port = "" # keep previous context - multiline syname
remote_port = '' remote_port = ""
remote_name = '' remote_name = ""
for line in output.splitlines(): for line in output.splitlines():
if header: if header:
# last line of header # last line of header
match = re.match(r'^--------- -+ .*$', line) match = re.match(r"^--------- -+ .*$", line)
if match: if match:
header = False header = False
fields_end = self._get_lldp_neighbors_fields_end(line) fields_end = self._get_lldp_neighbors_fields_end(line)
@@ -562,7 +563,7 @@ class S350Driver(NetworkDriver):
line_elems = self._get_lldp_neighbors_line_to_fields(line, fields_end) line_elems = self._get_lldp_neighbors_line_to_fields(line, fields_end)
# info owerflow to the other line # info owerflow to the other line
if line_elems[0] == '' or line_elems[4] == '' or line_elems[5] == '' : if line_elems[0] == "" or line_elems[4] == "" or line_elems[5] == "":
# complete owerflown fields # complete owerflown fields
local_port = local_port + line_elems[0] local_port = local_port + line_elems[0]
remote_port = remote_port + line_elems[2] remote_port = remote_port + line_elems[2]
@@ -573,16 +574,15 @@ class S350Driver(NetworkDriver):
remote_port = line_elems[2] remote_port = line_elems[2]
remote_name = line_elems[3] remote_name = line_elems[3]
local_port = canonical_interface_name( local_port = canonical_interface_name(local_port, s350_base_interfaces)
local_port,
s350_base_interfaces
)
neighbor = { neighbor = {
'hostname': remote_name, "hostname": remote_name,
'port': remote_port, "port": remote_port,
} }
neighbor_list = [neighbor, ] neighbor_list = [
neighbor,
]
neighbors[local_port] = neighbor_list neighbors[local_port] = neighbor_list
return neighbors return neighbors
@@ -601,7 +601,7 @@ class S350Driver(NetworkDriver):
def _get_lldp_neighbors_fields_end(self, dashline): def _get_lldp_neighbors_fields_end(self, dashline):
""" fields length are diferent device to device, detect them on horizontal lin """ """ fields length are diferent device to device, detect them on horizontal lin """
fields_end = [m.start() for m in re.finditer(' ', dashline)] fields_end = [m.start() for m in re.finditer(" ", dashline)]
fields_end.append(len(dashline)) fields_end.append(len(dashline))
return fields_end return fields_end
@@ -611,9 +611,9 @@ class S350Driver(NetworkDriver):
Safe-ish method to get the value from an 'lldp neighbors $IF' line. Safe-ish method to get the value from an 'lldp neighbors $IF' line.
""" """
try: try:
value = line.split(':')[1:][0].strip() value = line.split(":")[1:][0].strip()
except KeyError: except KeyError:
value = u'N/A' value = "N/A"
return value return value
@@ -628,58 +628,59 @@ class S350Driver(NetworkDriver):
if interface: if interface:
if interface == local_port: if interface == local_port:
entry = self._get_lldp_neighbors_detail_parse(local_port) entry = self._get_lldp_neighbors_detail_parse(local_port)
local_port = canonical_interface_name( local_port = canonical_interface_name(local_port, s350_base_interfaces)
local_port, details[local_port] = [
s350_base_interfaces entry,
) ]
details[local_port] = [entry, ]
else: else:
entry = self._get_lldp_neighbors_detail_parse(local_port) entry = self._get_lldp_neighbors_detail_parse(local_port)
local_port = canonical_interface_name( local_port = canonical_interface_name(local_port, s350_base_interfaces)
local_port, details[local_port] = [
s350_base_interfaces entry,
) ]
details[local_port] = [entry, ]
return details return details
def _get_lldp_neighbors_detail_parse(self, local_port): def _get_lldp_neighbors_detail_parse(self, local_port):
# Set defaults, just in case the remote fails to provide a field. # Set defaults, just in case the remote fails to provide a field.
remote_port_id, remote_port_description, remote_chassis_id, \ (
remote_system_name, remote_system_description, \ remote_port_id,
remote_system_capab, remote_system_enable_capab = (u'N/A',) * 7 remote_port_description,
remote_chassis_id,
remote_system_name,
remote_system_description,
remote_system_capab,
remote_system_enable_capab,
) = ("N/A",) * 7
output = self._send_command('show lldp neighbors {}'.format(local_port)) output = self._send_command("show lldp neighbors {}".format(local_port))
for line in output.splitlines(): for line in output.splitlines():
if line.startswith('Port ID'): if line.startswith("Port ID"):
remote_port_id = line.split()[-1] remote_port_id = line.split()[-1]
elif line.startswith('Device ID'): elif line.startswith("Device ID"):
remote_chassis_id = line.split()[-1] remote_chassis_id = line.split()[-1]
elif line.startswith('Port description'): elif line.startswith("Port description"):
remote_port_description = self._get_lldp_line_value(line) remote_port_description = self._get_lldp_line_value(line)
elif line.startswith('System Name'): elif line.startswith("System Name"):
remote_system_name = self._get_lldp_line_value(line) remote_system_name = self._get_lldp_line_value(line)
elif line.startswith('System description'): elif line.startswith("System description"):
remote_system_description = self._get_lldp_line_value(line) remote_system_description = self._get_lldp_line_value(line)
elif line.startswith('Capabilities'): elif line.startswith("Capabilities"):
caps = self._get_lldp_neighbors_detail_capabilities_parse(line) caps = self._get_lldp_neighbors_detail_capabilities_parse(line)
remote_port_id = canonical_interface_name( remote_port_id = canonical_interface_name(remote_port_id, s350_base_interfaces)
remote_port_id,
s350_base_interfaces
)
entry = { entry = {
'parent_interface': u'N/A', "parent_interface": "N/A",
'remote_port': remote_port_id, "remote_port": remote_port_id,
'remote_port_description': remote_port_description, "remote_port_description": remote_port_description,
'remote_chassis_id': remote_chassis_id, "remote_chassis_id": remote_chassis_id,
'remote_system_name': remote_system_name, "remote_system_name": remote_system_name,
'remote_system_description': remote_system_description, "remote_system_description": remote_system_description,
'remote_system_capab': caps, "remote_system_capab": caps,
'remote_system_enable_capab': caps, "remote_system_enable_capab": caps,
} }
return entry return entry
@@ -688,7 +689,7 @@ class S350Driver(NetworkDriver):
# Only the enabled capabilities are displayed. # Only the enabled capabilities are displayed.
try: try:
# Split a line like 'Capabilities: Bridge, Router, Wlan-Access-Point' # Split a line like 'Capabilities: Bridge, Router, Wlan-Access-Point'
capabilities = line.split(':')[1:][0].split(',') capabilities = line.split(":")[1:][0].split(",")
except KeyError: except KeyError:
capabilities = [] capabilities = []
@@ -697,8 +698,8 @@ class S350Driver(NetworkDriver):
# is the first character. # is the first character.
for cap in capabilities: for cap in capabilities:
cap = cap.strip() cap = cap.strip()
if cap == 'Repeater': if cap == "Repeater":
caps.append('r') caps.append("r")
else: else:
caps.append(cap[0]) caps.append(cap[0])
@@ -707,9 +708,9 @@ class S350Driver(NetworkDriver):
def get_ntp_servers(self): def get_ntp_servers(self):
"""Returns NTP servers.""" """Returns NTP servers."""
ntp_servers = {} ntp_servers = {}
output = self._send_command('show sntp status') output = self._send_command("show sntp status")
servers = re.findall(r'^Server\s*:\s*(\S+)\s*.*$', output, re.M) servers = re.findall(r"^Server\s*:\s*(\S+)\s*.*$", output, re.M)
for server in servers: for server in servers:
ntp_servers[server] = {} ntp_servers[server] = {}
@@ -721,18 +722,18 @@ class S350Driver(NetworkDriver):
null = chr(0) null = chr(0)
if self.device is None: if self.device is None:
return {'is_alive': False} return {"is_alive": False}
# Send a NUL byte to keep the connection alive. # Send a NUL byte to keep the connection alive.
try: try:
self.device.write_channel(null) self.device.write_channel(null)
return {'is_alive': self.device.remote_conn.transport.is_active()} return {"is_alive": self.device.remote_conn.transport.is_active()}
except (socket.error, EOFError): except (socket.error, EOFError):
# If we couldn't send it, the connection is not available. # If we couldn't send it, the connection is not available.
return {'is_alive': False} return {"is_alive": False}
# If we made it here, assume the worst. # If we made it here, assume the worst.
return {'is_alive': False} return {"is_alive": False}
@property @property
def dest_file_system(self): def dest_file_system(self):
+10 -10
View File
@@ -2,7 +2,7 @@
from setuptools import setup, find_packages from setuptools import setup, find_packages
__author__ = 'Jasper Lievisse Adriaanse <j@jasper.la>' __author__ = "Jasper Lievisse Adriaanse <j@jasper.la>"
with open("requirements.txt", "r") as fs: with open("requirements.txt", "r") as fs:
reqs = [r for r in fs.read().splitlines() if (len(r) > 0 and not r.startswith("#"))] reqs = [r for r in fs.read().splitlines() if (len(r) > 0 and not r.startswith("#"))]
@@ -21,15 +21,15 @@ setup(
long_description=long_description, long_description=long_description,
long_description_content_type="text/markdown", long_description_content_type="text/markdown",
classifiers=[ classifiers=[
'Topic :: Utilities', "Topic :: Utilities",
'License :: OSI Approved :: Apache Software License', "License :: OSI Approved :: Apache Software License",
'Programming Language :: Python', "Programming Language :: Python",
'Programming Language :: Python :: 3', "Programming Language :: Python :: 3",
'Programming Language :: Python :: 3.6', "Programming Language :: Python :: 3.6",
'Programming Language :: Python :: 3.7', "Programming Language :: Python :: 3.7",
'Programming Language :: Python :: 3.8', "Programming Language :: Python :: 3.8",
'Operating System :: POSIX :: Linux', "Operating System :: POSIX :: Linux",
'Operating System :: MacOS', "Operating System :: MacOS",
], ],
url="https://github.com/napalm-automation-community/napalm-s350", url="https://github.com/napalm-automation-community/napalm-s350",
include_package_data=True, include_package_data=True,
+1 -11
View File
@@ -1,6 +1,6 @@
[tox] [tox]
#envlist = py3{6,7,8},black,pylama,sphinx #envlist = py3{6,7,8},black,pylama,sphinx
envlist = py3{6,7,8},pylama envlist = py3{6,7,8},pylama,black
skip_missing_interpreters = true skip_missing_interpreters = true
[testenv] [testenv]
@@ -13,24 +13,14 @@ commands =
py.test --cov=napalm_s350 --cov-report term-missing -vs {posargs} py.test --cov=napalm_s350 --cov-report term-missing -vs {posargs}
[testenv:black] [testenv:black]
deps =
-rrequirements-dev.txt
commands = commands =
black --check --target-version py36 --line-length 100 --color --diff . black --check --target-version py36 --line-length 100 --color --diff .
[testenv:pylama] [testenv:pylama]
deps =
-rrequirements-dev.txt
commands = commands =
pylama . pylama .
[testenv:sphinx] [testenv:sphinx]
deps =
-rdocs/requirements.txt
commands = commands =
make doctest make doctest