[python]Connect to cisco ASA with pyserial

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.


from serial import Serial
from serial.serialutil import SerialException
from time import sleep
import re

class Console():
    def __init__(self, com_port, device_type):
        self.com_port = com_port
        self.device_type = device_type

    def test_port(self):
            # 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.
            # serial is slow, need to wait for data to be transmitted.
            # assume no enable password, in practical this will fail.
            # always remember to include \n for hitting the enter key
            # assume no password, press enter.
            # this is so manual... more logic has to be written.
            # 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')
            # this is the show version.
            console.write(b'show version\n')
            # this is estimated time to wait for the output to finish.
            # 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()
    elif not status:

Future improvement of the code is to use pexpect module to check for the expected prompt in order to apply the correct commands.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s