securecrt_tools.sessions

This module includes a collection of “session” objects that represent a session to a remote device. To some degree, a session object can be thought of as a tab in SecureCRT, since you can disconnect from a device and then connect to others with the same session object. These classes are intended as a wrapper around the SecureCRT Python API to simplify common tasks that are performed against network devices such as routers and switches. As with the Script class, there is also a DebugSession class as a part of this module to allow running the code by the local python interpreter so that the scripts can be debugged.

The base class is named “Session” is the parent for more specific session types and includes all methods that must be implemented by all sub-classes.

The primary subclass is called “CRTSession” which is specific to interacting with the Python API for SecureCRT. Whenever a script is launched from SecureCRT, this class should be used to interact with SecureCRT.

A second subclass called “DebugSession” is used to run scripts outside of SecureCRT, such as in an IDE. This is useful for debugging because you can run your script along with the IDE debugging tools while simulating the interactions with SecureCRT. The class has the same API as CRTSession so that no modifications are needed to run a script directly. For example, while a CRTSession may directly pull input from a device before processing it, if the script is launched from an IDE, the DebugSession object will instead prompt for a filename containing the same output that would be been received from the remote device. The script can then be debugged step-by-step to help the programmer better understand where their logic is having trouble with a particular output.

The Session Base Class

class securecrt_tools.sessions.Session

This is a base class for the other Session types. This class simply exists to enforce the required methods any sub-classes have to implement. There are also a couple methods that are common to all sessions so they are defined under this class and automatically inherited by the sub-classes.

create_output_filename(desc, ext='.txt', include_hostname=True, include_date=True, base_dir=None)

Generates a filename (including absoluate path) based on details from the session.

Parameters:
  • desc (str) – A short description to include in the filename (i.e. “show run”, “cdp”, etc)
  • ext (str) – (Optional) Extension for the filename. Default: “.txt”
  • include_hostname (bool) – (Optional) If true, includes the device hostname in the filename.
  • include_date (bool) – (Optional) Include a timestamp in the filename. The timestamp format is taken from the settings file. Default: True
  • base_dir (str) – (Optional) The directory where this file should be saved. Default: output_dir from settings.ini
Returns:

The generated absolute path for the filename requested.

Return type:

str

validate_os(valid_os_list)

This method checks if the remote device is running an OS in a list of valid OSes passed into the method. If the OS is not in the list then an exception is raised, which can either be allowed to cause the script to exit or be caught in a “try, except” statement and allow the script to take another action based on the result. If the remote OS is in the valid list, then nothing happens.

Parameters:valid_os_list – A list of OSs that

CRTSession Class

class securecrt_tools.sessions.CRTSession(script, tab, prompt_endings=None)

Bases: securecrt_tools.sessions.Session

This sub-class of the Session class is used to wrap the SecureCRT API to simplify writing new scripts. An instance of this class represents a tab in SecureCRT and the methods in this class are used to connect to devices, disconnect from devices or interact with devices that are connected within the specific SecureCRT tab that this object represents.

close()

A method to close the SecureCRT tab associated with this CRTSession.

disconnect(command='exit')

Disconnects the connected session by sending the “exit” command to the remote device. If that does not make the disconnect happen, attempt to force and ungraceful disconnect.

Parameters:command (str) – The command to be issued to the remote device to disconnect. The default is ‘exit’
end_cisco_session()

End the session by returning the device’s terminal parameters that were modified by start_session() to their previous values.

This should always be called before a disconnect (assuming that start_cisco_session was called after connect)

get_command_output(command)

Captures the output from the provided command and saves the results in a variable.

** NOTE ** Assigning the output directly to a variable causes problems with SecureCRT for long outputs. It will gradually get slower and slower until the program freezes and crashes. The workaround is to save the output directly to a file (line by line), and then read it back into a variable. This is the procedure that this method uses.

Keyword Arguments:
param command:Command string that should be sent to the device
type command:str
Returns:The result from issuing the above command.
Return type:str
is_connected()

Returns a boolean value that describes if the session is currently connected.

Returns:True if the session is connected, False if not.
Return type:bool
save(command='copy running-config startup-config')

Sends a “copy running-config startup-config” command to the remote device to save the running configuration.

send_config_commands(command_list, output_filename=None)

This method accepts a list of strings, where each string is a command to be sent to the device.

This method will send “conf t”, then all the commands from the list and finally send “end” to the device. If an output_filenameThe results returned from entering the commands into the device are written to a file.

NOTE: This method is new and does not have any error checking for how the remote device handles the commands you are trying to send. USE IT AT YOUR OWN RISK.

Parameters:
  • command_list (list) – A list of strings, where each string is a command to be sent. This should NOT include ‘config t’ or ‘end’. This is added automatically.
  • output_filename (str) – (Optional) If a absolute path to a file is specified, the config session output from applying the commands will be written to this file.
start_cisco_session(enable_pass=None)

Performs initial setup of the session to a Cisco device by detecting parameters (prompt, hostname, network OS, etc) of the connected device and modifying the terminal length if configured to do so in the settings file.

If the device is not at an enable prompt and an enable password is supplied, then this method will also enter enable mode on the device before proceeding.

This should always be called before trying to interact with a Cisco device so that the majority of other methods will work correctly. This should be one of the first calls in a script that is intended to run when already connected to the device, or called right after connecting to a device with the “connect_ssh” or similar method.

Parameters:enable_pass (str) – The enable password that should be sent if the device is not in enable mode.
telnet_login(username, password)

Looks for username and password prompts and then responds to them with the provided credentials. Should only be needed when doing a telnet login.

Parameters:
  • username (str) – The username that needs to be sent to the device.
  • password (str) – The password that needs to be sent to the device
write_output_to_file(command, filename, prompt_to_create=True)

Send the supplied command to the remote device and writes the output to a file.

This function was written specifically to write output line by line because storing large outputs into a variable will cause SecureCRT to bog down until it freezes. A good example is a large “show tech” output. This method can handle any length of output

Parameters:
  • command (str) – The command to be sent to the device
  • filename (str) – A string with the absolute path to the filename to be written.

DebugSession Class

class securecrt_tools.sessions.DebugSession(script)

Bases: securecrt_tools.sessions.Session

This class is used when the scripts are executed directly from a local Python installation instead of from SecureCRT. This class is intended to simulate connectivity to remote devices by prompting the user for what would otherwise be extracted from SecureCRT. For example, when this class tries to get the output from a show command, it will instead prompt the user for a location of a file with the associated output. This allows the scripts to be run directly in an IDE for development and troubleshooting of more complicated logic around parsing command outputs.

close()

A method to close the SecureCRT tab associated with this CRTSession. Does nothing but print to the console.

disconnect(command='exit')

Pretends to disconnects the connected session. Simply marks our session as disconnected.

Parameters:command (str) – The command to be issued to the remote device to disconnect. The default is ‘exit’
end_cisco_session()

End the session by returning the device’s terminal parameters that were modified by start_session() to their previous values.

This should always be called before a disconnect (assuming that start_cisco_session was called after connect)

get_command_output(command)

Captures the output from the provided command and saves the results in a variable.

** NOTE ** Assigning the output directly to a variable causes problems with SecureCRT for long outputs. It will gradually get slower and slower until the program freezes and crashes. The workaround is to save the output directly to a file (line by line), and then read it back into a variable. This is the procedure that this method uses.

Keyword Arguments:
param command:Command string that should be sent to the device
type command:str
Returns:The result from issuing the above command.
Return type:str
is_connected()

Returns a boolean value that describes if the session is currently connected.

Returns:True if the session is connected, False if not.
Return type:bool
save(command='copy running-config startup-config')

Pretends to send a “copy running-config startup-config” command to the remote device to save the running configuration. Only prints to the console.

send_config_commands(command_list, output_filename=None)

This method accepts a list of strings, where each string is a command to be sent to the device.

This method will pretend to send “conf t”, then all the commands from the list and finally send “end” to the device. If an output_filename is specified, the (fake) results returned from entering the commands into the (fake) device are written to a file.

Parameters:
  • command_list (list) – A list of strings, where each string is a command to be sent. This should NOT include ‘config t’ or ‘end’. This is added automatically.
  • output_filename (str) – (Optional) If a absolute path to a file is specified, the config session output from applying the commands will be written to this file.
start_cisco_session(enable_pass=None)

Performs initial setup of the session to a Cisco device by detecting parameters (prompt, hostname, network OS, etc) of the connected device and modifying the terminal length if configured to do so in the settings file.

Always assumes that we are already in enable mode (privilege 15)

This should always be called before trying to interact with a Cisco device so that the majority of other methods will work correctly. This should be one of the first calls in a script that is intended to run when already connected to the device, or called right after connecting to a device with the “connect_ssh” or similar method.

Parameters:enable_pass (str) – The enable password that should be sent if the device is not in enable mode.
write_output_to_file(command, filename, prompt_to_create=True)

Send the supplied command to the remote device and writes the output to a file.

This function was written specifically to write output line by line because storing large outputs into a variable will cause SecureCRT to bog down until it freezes. A good example is a large “show tech” output. This method can handle any length of output

Parameters:
  • command (str) – The command to be sent to the device
  • filename (str) – A string with the absolute path to the filename to be written.

Session Class Exceptions:

exception securecrt_tools.sessions.InteractionError

An exception type used when an expected response isn’t received when interacting with a device.

exception securecrt_tools.sessions.UnsupportedOSError

An exception type used when the remote device is running an OS that isn’t supported by the script.