So on previous post I wrote a simple code to test if the serial com port is working, now I extended the code with some function.
I create a class for the serial so that more than one object can be created not just for a single Cisco ASA. The below code snippet gave a simple illustration on how to extend the feature with pyserial.
console.py
from serial import Serial from serial.serialutil import SerialException from time import sleep import re class Console(): ''' https://www.cisco.com/c/en/us/support/docs/dial-access/asynchronous-connections/9321-terminal-settings.html ''' def __init__(self, com_port, device_type): self.com_port = com_port self.device_type = device_type def test_port(self): try: Serial(port=self.com_port) # returns a tuple, one is the boolean the other is whether error is None or not. return True, None except SerialException as e: return False, e def show_version(self): with Serial(port=self.com_port) as console: # press enter. console.write(b'\n') # serial is slow, need to wait for data to be transmitted. sleep(1) # assume no enable password, in practical this will fail. # always remember to include \n for hitting the enter key console.write(b'enable\n') sleep(1) # assume no password, press enter. # this is so manual... more logic has to be written. console.write(b'\n') sleep(1) # issue terminal pager 0 command so that all information will be presented # else need to press enter until the end of file. if self.device_type == 'cisco_asa': console.write(b'terminal pager 0\n') sleep(1) # this is the show version. console.write(b'show version\n') # this is estimated time to wait for the output to finish. sleep(3) # the return value is a byte. # get all the stream of bytes output_in_bytes = console.inWaiting() # read the collected byte stream show_version_output = console.read(output_in_bytes) # convert bytes to string. return show_version_output.decode('utf-8')
The test code is:
from console import Console if __name__ == '__main__': cisco_fw = Console('com4', 'cisco_asa') status, err = cisco_fw.test_port() if status: output = cisco_fw.show_version() print(output) elif not status: print(err)
Future improvement of the code is to use pexpect
module to check for the expected prompt in order to apply the correct commands.