Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Python
import serial
import time

# Serial port configuration
ser = serial.Serial("/dev/ttyUSB0", timeout=1)
print(f"Connecting to {ser.name}...")

# Strings for prompt detection
initPrompt = "Initializing Flash"
swPrompt = "switch:"
ynPrompt = " (y/n)?"

# Function to wait for specific prompt and send command
def wait_for_prompt_and_send(prompt, command):
    while True:
        response = ser.read_until(prompt.encode("utf-8")).decode("utf-8")
        if prompt in response:
            print(f"Found prompt: {prompt}")
            ser.write(command)
            ser.write(b"\n")
            break

# Connect and send initial break commands
ser.write(b"\r")
print("Sent carriage return...")
time.sleep(0.5)
wait_for_prompt_and_send(initPrompt, b"\x03")  # break command

# Initialize flash
wait_for_prompt_and_send(swPrompt, b"flash_init\n\n")

# Delete vlan.dat
wait_for_prompt_and_send(swPrompt, b"del flash:vlan.dat\n")
wait_for_prompt_and_send(ynPrompt, b"y\n")

# Delete config.text
wait_for_prompt_and_send(swPrompt, b"del flash:config.text\n")
wait_for_prompt_and_send(ynPrompt, b"y\n")

ser.close()


What I have tried:

I have to reset a lot of old Cisco switches so I wanted to automate the process.

Instead of holding down the physical button on the switch, the script should issue a break command after the program ran the initPrompt initializing flash. However, it doesn't do that. All I see on the Python console is that it sent the carriage return and found the prompt: initializing flash. When I open the SecureCRT session and check the status of the startup, the switch goes through the normal boot so the break definitely didn't work.

Win 10 & Python 3.10
Posted
Updated 17-Aug-23 7:55am
v2
Comments
Richard MacCutchan 16-Aug-23 8:12am    
It's not possible to guess why this may not be working. I suggest you run the code in the Python debugger so you can see exactly what is happening.
Member 15627495 18-Aug-23 10:00am    
you have to debug : -trace your vars-

write few lines more, to -display- your input within the loop

you will know where it stop

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900