Paramiko:从远程执行命令的标准输出中读取

所以我正在与paramiko一起进行一些基本的SSH测试,并且没有将任何输出输出到stdout中。这是我的代码。

import paramiko

client=paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

com="ls ~/desktop"

client.connect('MyIPAddress',MyPortNumber, username='username', password='password')

output=""

stdin, stdout, stderr = client.exec_command(com)

print "ssh succuessful. Closing connection"

client.close()

print "Connection closed"

stdout=stdout.readlines()

print stdout

print com

for line in stdout:

output=output+line

if output!="":

print output

else:

print "There was no output for this command"

因此,每当我运行此命令时,都会执行该命令(如执行cp之类的操作所看到的那样,文件将被复制),但是我始终会收到“此命令无输出”的信息。当输出stdout =

stdout.readlines()时,输出为[]。另外,如果我将打印语句添加到for循环中,它将永远不会运行。有人可以帮我吗?谢谢!

回答:

在阅读以下行之前,您已经关闭了连接:

import paramiko

client=paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

com="ls ~/desktop"

client.connect('MyIPAddress',MyPortNumber, username='username', password='password')

output=""

stdin, stdout, stderr = client.exec_command(com)

print "ssh succuessful. Closing connection"

stdout=stdout.readlines()

client.close()

print "Connection closed"

print stdout

print com

for line in stdout:

output=output+line

if output!="":

print output

else:

print "There was no output for this command"

以上是 Paramiko:从远程执行命令的标准输出中读取 的全部内容, 来源链接: utcz.com/qa/406945.html

回到顶部