Skip to content

Instantly share code, notes, and snippets.

@Tes3awy
Forked from TannerRayMartin/serial_test1.py
Last active December 31, 2021 14:28
Show Gist options
  • Save Tes3awy/c7b95c54238e30122cf98dad9aad03bd to your computer and use it in GitHub Desktop.
Save Tes3awy/c7b95c54238e30122cf98dad9aad03bd to your computer and use it in GitHub Desktop.
Connecting to a Cisco switch via console cable through a serial port with a laptop using Python3 (pySerial)
__author__ = "Tanner Ray Martin & Osama Abbas"
__version__ = "1.1.0"
import time
import serial
# Creating your serial object
ser_conn = serial.Serial(
port="COM3", # COM is on windows, linux is different
baudrate=serial.Serial.BAUDRATES[12], # 9600
parity=serial.PARITY_NONE, #'N'
stopbits=serial.STOPBITS_ONE, # 1
bytesize=serial.EIGHTBITS, # 8
timeout=20, # 20 seconds seems to be a good timeout, may need to be increased
)
# Open your serial object
ser_conn.isOpen()
# In this case it returns str COM3
print(ser_conn.name)
# First command (hitting enter)
command = "\r\n"
# Convert str to binary (commands sent to switch must be binary)
command = str.encode(command)
# Send the command to the switch
ser_conn.write(command)
# Wait a sec
time.sleep(1)
ser_conn.inWaiting()
# Get the response from the switch
input_data = ser_conn.read(225) # (how many bytes to limit to read)
# Convert binary to str
input_data = input_data.decode("utf-8", "ignore")
# Print response
print(input_data)
# Create a loop
while True:
# Enter your own command
command = input(":: ")
# Type 'exit' to end serial session with the switch
if command == "exit":
ser_conn.close()
exit()
else:
# Convert command to binary
command = str.encode(command + "\r\n")
# Send command
ser_conn.write(command)
# Set response variable (empty binary str)
out = b""
# Take a short nap
time.sleep(1)
# While response is happening (timeout hasnt expired)
while ser_conn.inWaiting() > 0:
# Trying to read one line at a time (100 bytes at a time)
out = ser_conn.readline(100)
# Converting response to str
out = out.decode("utf-8", "ignore")
# Printing response if not empty
if out != "":
print(out)
# Repeat until timeout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment