python - 有人对 telnetlib.expect() 有好感吗?

标签 python telnetlib

我正在编写一个库来支持远程登录到远程服务器并运行应用程序。

在建立连接、取回数据、解析等方面一切进展顺利(至少与通过文本界面与程序通信一样顺畅)。

一个app如果正常进入会改变光标,如果失败则保留原来的光标(我不写app,我只需要使用它们。)

当所述应用程序正确启动时,这没有问题:

promptB = "hello(x)# "   # Yes, the space at the end is intentional
response = tn_conn.cmd("app_name\n", prompt=promptB)

我想用提示变化(或缺少提示变化)来检测程序是否启动失败。我认为这将是尝试 telnetlib 的 expect() 的绝好机会,因为 expect() 允许传递字符串列表以在响应中进行匹配。

但是,我无法让它工作:

promptA = "hello(x)# "   # Yes, the space at the end is intentional
promptB = "hello> "      # Yes, the space at the end is intentional

tn_conn.write("app_name\n")
which_prompt, mo, response = self.tn_conn.expect([promptA, promptB], timeout=3)

无论应用启动成功与否,expect命令总是超时。

哪个=“-1”

莫=无

response = "mumble mumble\r\r\n other stuff\r\n\r\nhello# "

文档说可以将字符串或正则表达式对象传递给 expect(我传递的是字符串),所以我是不是遗漏了什么?查看 telnetlib 代码表明它调用的是 re.search(),而不是 re.match(),因此这似乎不是问题所在。

任何人都可以就我做错了什么提出建议吗?

编辑 在提示示例中添加了括号,以更好地说明 expect() 未按预期工作的原因。

最佳答案

不要忘记,如果您在 Python 中使用正则表达式,您始终可以使用原始 (r'my string') 方法,而不是添加所有转义符;使其更具可读性。

关于python - 有人对 telnetlib.expect() 有好感吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7814961/

相关文章:

python - PeeWee 是否支持与 MySQL View 的交互?

Python - 在路由器上远程登录并列出完整结果(点击空格键)

Python Telnet 脚本

python - 如何从 Python 中的 telnet 查询读取多行?

没有 ascii 编码和 b 前缀的 Python3 : Is there a way to use telnetlib like in python2,?

python - Facebook 时间戳到 Python DateTime 对象

python - 如何获取 Distutils compile() 函数使用的实际命令?

python - flask - 404 未找到

python - 在 Jupyter 笔记本中默认配置第一个单元格

python - 如何使用 telnetlib 打印 "tar"执行的输出,直到它完成?