通过串行通信自动登录操作

Automating log-in action through serial communication

我正在尝试为我通过 serial 与之通信的设备自动执行登录功能。为了到达 login: 提示符,我必须在设备启动时按回车键,然后在一段时间后 login: 提示符将出现,一旦程序发现 'login:' 字符串,它就会输入用户名(或至少这是计划)。输入正确的用户名后会出现Password:提示,如果我输入正确的密码我成功登录到设备,如果我输入错误的密码我必须重新开始(这意味着重新输入用户名).另外,如果我第一次尝试登录失败,login: 提示会更改为 username:

到目前为止我已经做到了,但是

import serial
import re
from time import sleep
import time

ser = serial.Serial('COM3', timeout=1)
ser.baudrate = 115200

def auto_login():
    while True:
        output = ser.read(10000).decode('utf-8', 'ignore')
        testmode_command = ser.write("\r\n".encode())
        print(output)
        if "1 : press [Enter] for test mode / [Esc+Enter] for plain Linux" in output:
            ser.write(testmode_command)
        if " login:" in output:
            break



def login_repeat():
    login = b"root \r\n"
    output = ser.read(10000).decode('utf-8', 'ignore')
    print(output)
    if " login:" in output:
        ser.write(login)
    if "Username:" in output:
        ser.write(login)

def pass_word():
    password = b"p \r\n"
    time.sleep(0.1)
    output = ser.read(10000).decode('utf-8', 'ignore')
    print(output)
    if "Password:" in output:
        ser.write(password)

我得到的结果是:

Login incorrect
Username: 
root 

System starting up, please try later

Login incorrect
Username: 
root 

出于某种原因,我看起来首先发送的是 \r\n 命令而不是用户名,然后是命令。知道如何解决这个问题吗?

正如直觉,你确定,你没有缓冲问题。我不知道串行模块,但图书馆可能会发送 "Enter" 和登录信息。 这将导致 "Enter" 作为用户名。

快速搜索得出这个答案:

您可以尝试显式刷新缓冲区。

另一方面,我想知道为什么您没有事先在串行线路上输入 "Enter" 键就进入登录提示。你确定,你需要在线上的 [​​=19=] 键吗?

在发送命令之前添加 time.sleep(0.1),如下所示:

time.sleep(0.1)
ser.write(b"root")
time.sleep(0.1)
ser.write('\r'.encode())