简体   繁体   English

使用子进程和通讯在Telnet连接上执行命令

[英]Using Subprocess and Communicate to execute commands on Telnet connection

This is my first query on StackExchange. 这是我对StackExchange的第一个查询。 Kindly excuse, if my question is already been raised and answered. 请原谅,如果我的问题已经有人提出并回答了。 If so, kindly point me to the same. 如果是这样,请指点相同。

Query: I am trying to establish the telnet connection to a board and then would like run a app after that. 查询:我正在尝试建立与开发板的telnet连接,然后想在那之后运行一个应用程序。 I would like to capture both STDOUT and STDERR during whole process. 我想在整个过程中同时捕获STDOUT和STDERR。 Below is the snippet of my code 以下是我的代码片段

Code Snippet: 代码段:

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')

At step (4), i tried printing the values of stdout and stderr to see whether the application 'app' has run or not. 在步骤(4),我尝试打印stdout和stderr的值,以查看应用程序“ app”是否已运行。 Unfortunately, it has not even executed the 'p.communicate()' line. 不幸的是,它甚至没有执行'p.communicate()'行。

If any one has encountered similar problem or know the solution, kindly help me to fix the issue. 如果有人遇到类似问题或知道解决方案,请帮助我解决问题。

Thank you!! 谢谢!!

Terminate your strings with \\n instead of \\r? 用\\ n而不是\\ r终止字符串?

Consider using telnetlib, instead of rolling your own w/ subprocess? 考虑使用telnetlib,而不是滚动自己的w /子进程?

And finally, if you can run an ssh server on this board, you'll be able to use paramiko and ssh channels, which will help avoid some headaches down the road. 最后,如果您可以在此板上运行ssh服务器,则可以使用paramiko和ssh通道,这将有助于避免日后的麻烦。

You can use Pexpect Library to get your task done. 您可以使用Pexpect库完成任务。

Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup scripts for duplicating software package installations on different servers. Pexpect可用于自动化交互应用程序,例如ssh,ftp,passwd,telnet等。它可用于自动化安装脚本,以在不同服务器上复制软件包安装。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM