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()
`我必须重置很多旧的思科交换机,所以我想自动化该过程。
脚本不应按住开关上的物理按钮,而应在程序运行 initPrompt 初始化闪存后发出中断命令。然而,它并没有这样做。我在python控制台上看到的只是它发送了回车符,发现提示:正在初始化flash。当我打开 SecureCRT 会话并检查启动状态时,交换机会进行正常启动,因此中断肯定不起作用。
Win 10 和 Python 3.10`
查看文档(https://pyserial.readthedocs.io/en/latest/pyserial_api.html),您可以尝试“send_break(duration=0.25)”参数,也许可以稍微调整一下持续时间值.