Files
napalm-s350/napalm_s350/s350.py
T

296 lines
9.5 KiB
Python

# -*- coding: utf-8 -*-
# Copyright 2018 Jasper Lievisse Adriaanse. 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 Cisco S350 devices.
Read https://napalm.readthedocs.io for more information.
"""
from __future__ import print_function
from __future__ import unicode_literals
import netaddr
import re
import socket
from netmiko import ConnectHandler
from napalm.base import NetworkDriver
from napalm.base.exceptions import (
ConnectionException,
SessionLockedException,
MergeConfigException,
ReplaceConfigException,
CommandErrorException,
)
from napalm.base.utils import py23_compat
class S350Driver(NetworkDriver):
"""Napalm driver for S350."""
def __init__(self, hostname, username, password, timeout=60, optional_args=None):
"""Constructor."""
self.device = None
self.hostname = hostname
self.username = username
self.password = password
self.timeout = timeout
if optional_args is None:
optional_args = {}
self._dest_file_system = optional_args.get('dest_file_system', None)
# 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,
}
# Allow for passing additional Netmiko arguments
self.netmiko_optional_args = {}
for k, v in netmiko_argument_map.items():
try:
self.netmiko_optional_args[k] = optional_args[k]
except KeyError:
pass
self.port = optional_args.get('port', 22)
self.device = None
def open(self):
"""Open a connection to the device."""
self.device = ConnectHandler(device_type='cisco_s300',
host=self.hostname,
username=self.username,
password=self.password,
**self.netmiko_optional_args)
self.device.enable()
def _discover_file_system(self):
try:
return self.device._autodetect_fs()
except Exception:
msg = "Netmiko _autodetect_fs failed (to work around 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 output.strip()
except (socket.error, EOFError) as e:
raise ConnectionClosedException(str(e))
def _parse_uptime(self, uptime_str):
"""Parse an uptime string into number of seconds"""
uptime_str = uptime_str.strip()
days, timespec = uptime_str.split(',')
hours, minutes, seconds = timespec.split(':')
uptime_sec = (int(days) * 86400) + (int(hours) * 3600) + (int(minutes) * 60) + int(seconds)
return uptime_sec
def get_config(self, retrieve='all'):
"""
get_config for S350. Since this firmware doesn't support a candidate
configuration we leave it empty.
"""
configs = {
'startup': '',
'running': '',
'candidate': '',
}
if retrieve in ('all', 'startup'):
output = self._send_command('show startup-config')
configs['startup'] = output
if retrieve in ('all', 'running'):
output = self._send_command('show running-config')
configs['running'] = output
return configs
def get_facts(self):
"""Return a set of facts from the device."""
serial_number, fqdn, os_version, hostname, domain_name = ('Unknown',) * 5
# Submit commands to the device.
show_ver = self._send_command('show version | include Version')
show_sys = self._send_command('show system')
show_inv = self._send_command('show inventory')
show_hosts = self._send_command('show hosts | begin Default Domain Table')
show_int_st = self._send_command('show interface status | include gi')
# os_version
for line in show_ver.splitlines():
# First version line is the active version
if 'Version' in line:
_, os_version = line.split('Version: ')
break
# hostname, uptime
for line in show_sys.splitlines():
if line.startswith('System Name:'):
_, hostname = line.split('System Name:')
hostname = hostname.strip()
elif line.startswith('System Description:'):
_, model = line.split('System Description:')
model = model.strip()
elif line.startswith('System Up Time (days,hour:min:sec):'):
_, uptime_str = line.split('System Up Time (days,hour:min:sec):')
uptime = self._parse_uptime(uptime_str)
# serial_number
for line in show_inv.splitlines():
if 'SN:' in line:
serial_number = line.split('SN: ')[-1]
break
# fqdn
domain_line = show_hosts.splitlines()[4]
domainname = domain_line.split()[0]
fqdn = '{0}.{1}'.format(hostname, domainname)
# interface_list
interfaces = []
for line in show_int_st.splitlines():
interfaces.append(py23_compat.text_type(line.split()[0]))
return {
'fqdn': py23_compat.text_type(fqdn),
'hostname': py23_compat.text_type(hostname),
'interface_list': interfaces,
'model': py23_compat.text_type(model),
'os_version': py23_compat.text_type(os_version),
'serial_number': py23_compat.text_type(serial_number),
'uptime': uptime,
'vendor': u'Cisco',
}
def get_interfaces_ip(self):
"""Returns all configured interface IP addresses."""
interfaces = {}
show_ip_int = self._send_command('show ip int | include (UP|DOWN)')
# Limit to valid interfaces (i.e. ignore vlan 1)
valid_interfaces = [i for i in show_ip_int.splitlines() if i.split()[-1] == 'Valid']
for interface in valid_interfaces:
network, name = interface.split()[:2]
ip = netaddr.IPNetwork(network)
family = 'ipv{0}'.format(ip.version)
interfaces[name] = {
family: {
str(ip.ip): {
'prefix_length': ip.prefixlen
}
}
}
return interfaces
def get_lldp_neighbors(self):
"""get_lldp_neighbors implementation for s350"""
neighbors = {}
output = self._send_command('show lldp neighbors | begin \ \ Port')
for line in output.splitlines()[2:]:
line_elems = line.split()
local_port = line_elems[0]
remote_port = line_elems[2]
remote_name = line_elems[3]
neighbors[local_port] = {
'hostname': remote_name,
'port': remote_port,
}
return neighbors
def get_ntp_servers(self):
"""get_ntp_servers implementation for S350"""
ntp_servers = {}
output = self._send_command('show sntp status | include Server')
for line in output.splitlines():
ntp_servers[line.split()[2]] = {}
return ntp_servers
def is_alive(self):
"""Returns an indication of the state of the connection."""
null = chr(0)
if self.device is None:
return {'is_alive': False}
# Send a NUL byte to keep the connection alive.
try:
self.device.write_channel(null)
return {'is_alive': self.device.remote_conn.transport.is_active()}
except (socket.error, EOFError):
# If we couldn't send it, the connection is not available.
return {'is_alive': False}
# If we made it here, assume the worst.
return {'is_alive': False}
@property
def dest_file_system(self):
# First ensure we have an open connection.
if self.device and self._dest_file_system is None:
self._dest_file_system = self._discover_file_system()
return self._dest_file_system