Base class
Base class – 30-40 minutes
This can be a confusing topic if you don’t already have experience with object-oriented programming. It takes some reading, some thinking, maybe some re-reading, and the concepts will come to you. It’s not easy, but it’s definitely worth it. We’re going to create a base class that we are going to inherit from in our SSHHost class. We’re implementing inheritance.
You might wonder why we would go about this. Why break something that works so delightfully well?
There are some things that we need to do, like writing to a log, that are the same no matter what protocol we use to connect to host devices. By moving those capabilities to a base class we can reuse the code more easily. Capabilities in the base class will be available in the derived classes. So we can put a log function/method into the base class and reuse the code from any or all of the derived classes. Let’s see how that works.
Here’s a whole base class. Give it a quick look and then we’ll break it down.
class HostDevice(object):
__metaclass__ = abc.ABCMeta
def __init__(self, parameters):
self.run_time = datetime.now()
self.log_directory = "Log"
self.parameters = parameters
required_parameters = ['device_name', 'user_name', 'password']
optional_parameters = ['key_file']
## Make sure we have all of the parameters we need
for param in required_parameters:
if param not in self.parameters:
raise Exception('{0} is missing from parameters to HostDevice'.format(param))
## Make sure we don't accept any parameters we don't recognize
all_parameters = required_parameters + optional_parameters
for key in self.parameters:
if key not in all_parameters:
raise Exception("Found '{0}' in the parameters to HostDevice, but I don't recognize that parameter.".format(key))
self.device_name = self.parameters['device_name']
self.user_name = self.parameters['user_name']
if 'password' in self.parameters:
self.password = self.parameters['password']
@abc.abstractmethod
def connect(self):
"""Establishes a connection to the host"""
def log_filename_for_command(self, command):
device = self.device_name.replace('.', '_')
filename = self.slugify("{0}_{1}_{2}".format(device, command, datetime.strftime(self.run_time, '%Y%m%d_%H%M%S'))) + '.log'
filename = os.path.join(self.log_directory, filename)
if not os.path.exists(self.log_directory):
os.makedirs(self.log_directory)
return filename
def slugify(self, value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
Found at: http://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename-in-python
"""
import unicodedata
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = value.decode('ascii')
value = re.sub('[^\w\s-]', '', value.strip().lower())
value = re.sub('[-\s]+', '_', value)
return value
@abc.abstractmethod
def read_config_and_save_to_file(self):
"""Reads the configuration from the host"""
We start out with a pretty standard class definition statement for HostDevice. Then we have a new concept:
__metaclass__ = abc.ABCMeta
We’re using Python’s built-in Abstract Base Class (ABC) infrastructure to tell Python that this class is an ABC. Say what? That just means that the base class is abstract and cannot be instantiated. That means you cannot create a HostDevice object directly.
# Not allowed because HostDevice is an abstract base class host = HostDevice()
How would Python know that HostDevice is an abstract class? We let Python know what’s up by using the abstractmethod decorator. For example:
@abc.abstractmethod
def connect(self):
"""Establishes a connection to the host"""
What’s happening here is that we are creating the connect() method in HostDevice, but we are also specifying that the method is abstract. Because it is abstract any class that inherits from HostDevicemust implement a connect() method. Derived classes must implement abstract methods. Derived classes do not need to implement non-abstract methods, but may override them if appropriate.
When designing a family of classes we try to figure out the lowest common denominators. For example, we know that regardless of whether we use SSH or Telnet we will always need to connect to a host device. But how we connect is different based on whether we’re using SSH or Telnet. So we take the idea of connecting and represent it as the abstract base method connect().
In other cases, like log_filename_for_command, the code is always the same regardless of the protocol we use to connect to the host device. So we can implement the method in the base class and let it be shared by derived classes.
Now let’s take a look at an SSHHost class that is derived from our base class. Again, give it a read through and we’ll discuss on the other side.
class SSHHost(HostDevice):
def connect(self):
successfully_connected = False
try:
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ## to avoid missing_host_key error
if self.password == None:
import getpass
print("Hey, I don't have the password for '{0}' on '{1}'. Please enter it...".format(self.user_name, self.device_name))
self.password = getpass.getpass()
print("You entered a password of '{0}'".format(self.password))
print("Attempting to connect {0}@{1} / {2}".format(self.user_name, self.device_name, self.password))
self.ssh.connect(self.device_name, username=self.user_name, password=self.password, allow_agent=False,
look_for_keys=False)
self.channel = self.ssh.invoke_shell()
successfully_connected = True
except paramiko.SSHException as ex:
print(' -= -= -= -= -= An exception occurred =- =- =- =- =-')
print("Failure connecting to '{0}' for '{1}': {2}".format(self.device_name, self.user_name, str(ex)))
self.ssh = None
self.channel = None
return successfully_connected
def read_config_and_save_to_file(self):
if self.connect():
self.send_command_and_get_response('enable')
self.send_command_and_get_response('testpix')
self.send_command_and_get_response('terminal pager 0')
self.perform_command_and_log_results("show run")
def perform_command_and_log_results(self, cmd):
output = self.send_command_and_get_response(cmd)
log_file = self.log_filename_for_command(cmd)
print(' Writing to {0}'.format(log_file))
f = open(log_file, 'w')
for (idx, line) in enumerate(output):
f.write(str(line))
f.close()
def get_command_results(self):
## http://joelinoff.com/blog/?p=905
channel = self.channel
interval = 0.1
maxseconds = 10
maxcount = maxseconds / interval
bufsize = 1024
# Poll until completion or timeout
# Note that we cannot directly use the stdout file descriptor
# because it stalls at 64K bytes (65536).
input_idx = 0
timeout_flag = False
start = datetime.now()
start_secs = time.mktime(start.timetuple())
output = ''
channel.setblocking(0)
while True:
if channel.recv_ready():
data = channel.recv(bufsize).decode('ascii')
output += data
if channel.exit_status_ready():
break
# Timeout check
now = datetime.now()
now_secs = time.mktime(now.timetuple())
et_secs = now_secs - start_secs
if et_secs > maxseconds:
timeout_flag = True
break
rbuffer = output.rstrip(' ')
if len(rbuffer) > 0 and (rbuffer[-1] == '#' or rbuffer[-1] == '>'): ## got a Cisco command prompt
break
time.sleep(0.200)
if channel.recv_ready():
data = session.recv(bufsize)
output += data.decode('ascii')
return output
def send_command_and_get_response(self, cmd):
if not cmd.endswith("\n"):
cmd += "\n"
self.channel.send(cmd)
results = self.get_command_results()
return results
Note that we are actually implementing the connect() method. The method has the code that is specific to an SSH implementation. In order to use SSHHost we have to implement each of the abstract methods.
We have mostly tried, first, to figure out the features we need. And, second, we decided on whether we can implement the features in the base class or if they need to be implemented in the derived class.
Now we’ve done some nifty
refactoring and laid the groundwork to add a new protocol so we can support some other types of host devices.
