python - 通过串行通信自动执行登录操作
问题描述
我正在尝试为我与之通信的设备自动化登录功能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
命令而不是用户名,然后是命令。知道如何解决这个问题吗?
解决方案
就像预感一样,您确定,您没有缓冲问题。我不知道串行模块,但库可能会将“Enter”与登录信息一起发送。这将导致“Enter”作为用户名。
快速搜索提出了这个答案:https ://stackoverflow.com/a/12892221/4252584
您可能会尝试显式刷新缓冲区。
另一方面,我想知道为什么您在串行线路上没有事先“Enter”键就进入登录提示。你确定,你需要在线上的“Enter”键吗?
推荐阅读
- api - 我试图简单地连接到 ibapi(Interactive Brokers API),但我在使用 Flask 时遇到了一些技术问题
- python - 从 Outlook REST API v1.0 中的基本身份验证迁移到 v2.0
- android - 全局对话框 - 如何?
- javascript - Vba to IE Click JavaScript button no Id
- wso2 - WSO2 - EI 6.2.0 - 使用 EI 配置 Oracle AQ JMS 数据库以向/从 Oracle AQ JMS 发布/使用消息
- linux - 使用 r 扩展时在 Linux 上无头运行 Netlogo Behaviorspace 时不会停止
- c# - 远程服务器返回错误:(415) Unsupported Media Type using API in asp.net
- php - 在php中从exec发送电子邮件
- java - Java - 不接受硬币的自动售货机
- java - 为什么反射 API 会为现有的枚举构造函数抛出 NoSuchMethodException?