【问题标题】:Using Subprocess and Communicate to execute commands on Telnet connection使用 Subprocess 和 Communicate 在 Telnet 连接上执行命令
【发布时间】:2015-01-10 11:45:07
【问题描述】:

这是我在 StackExchange 上的第一个查询。如果我的问题已经被提出并回答,请原谅。如果是这样,请指点我。

查询: 我正在尝试建立与板的 telnet 连接,然后想在此之后运行应用程序。我想在整个过程中同时捕获 STDOUT 和 STDERR。下面是我的代码的sn-p

代码片段:

import subprocess
import time

#1. Establish the subprocess 
commandlist = ["telnet"] + ["10.11.12.13"]
p = subprocess.Popen(commandlist,
                     stdin = subprocess.PIPE,
                     stdout = subprocess.PIPE,
                      stderr = subprocess.PIPE)
#2. Give the login name. There is no password
p.stdin.write("root\r")
#3. Adding this for sync to avoid any overlap
time.sleep(1)
#4. Invoke the communicate to execute the application from a specied path on 10.11.12.13 system
stdout, stderr = p.communicate('sh /mnt/path/app\r')

在第 (4) 步,我尝试打印 stdout 和 stderr 的值以查看应用程序“app”是否已运行。不幸的是,它甚至没有执行 'p.communicate()' 行。

如果有人遇到类似问题或知道解决方案,请帮助我解决问题。

谢谢!!

【问题讨论】:

  • it has not even executed the 'p.communicate()' line.。输出是什么?
  • @laike9m:下面是输出#STDOUT Trying 10.11.12.13... Connected to 10.11.12.135。 (none) login: root # STDERR 连接被外部主机关闭。
  • @laike9m:我尝试从我的 linux 服务器手动连接到硬件,但没有看到任何此类错误/消息。你对此有什么进一步的建议吗?.. 谢谢.. 而且即使我通过“退出”命令退出硬件,也会出现由外国主机关闭的情况

标签: python subprocess telnet


【解决方案1】:

您可以使用 Pexpect 库来完成您的任务。

Pexpect 可用于自动化交互式应用程序,例如 ssh、ftp、passwd、telnet 等。它可用于自动化安装脚本,以便在不同服务器上复制软件包安装。

https://pexpect.readthedocs.io/en/stable/

【讨论】:

    【解决方案2】:

    用 \n 而不是 \r 来结束你的字符串?

    考虑使用 telnetlib,而不是滚动您自己的 w/ 子进程?

    最后,如果您可以在此板上运行 ssh 服务器,您将能够使用 paramiko 和 ssh 通道,这将有助于避免一些令人头疼的问题。

    【讨论】:

    • 感谢您的回复和建议。我也尝试过使用 '\n' 。但结果是一样的。我正在尝试的系统/硬件没有 ssh。我只能在子进程中使用 telnet。
    猜你喜欢
    • 1970-01-01
    • 2019-12-16
    • 2013-01-30
    • 2012-12-30
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 2016-03-01
    • 2012-01-14
    相关资源
    最近更新 更多