首页 > 解决方案 > 通过串行通信自动执行登录操作

问题描述

我正在尝试为我与之通信的设备自动化登录功能serial。为了达到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命令而不是用户名,然后是命令。知道如何解决这个问题吗?

标签: pythonpython-3.xautomationpyserial

解决方案


就像预感一样,您确定,您没有缓冲问题。我不知道串行模块,但库可能会将“Enter”与登录信息一起发送。这将导致“Enter”作为用户名。

快速搜索提出了这个答案:https ://stackoverflow.com/a/12892221/4252584

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

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


推荐阅读