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

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

本文介绍了Paramiko:从远程执行命令的标准输出中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在使用 paramiko 进行一些基本的 SSH 测试,但我没有将任何输出输入到标准输出中.继承人我的代码.

so I was working with paramiko for some basic SSH testing and I'm not getting any output into stdout. Heres my code.

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 循环中添加一个打印语句,它永远不会运行.有人可以帮我吗?谢谢!

So whenever I run this, the command is executed (as seen by if I do something like a cp, the file is copied), but I always get "There was no output for this command". When stdout=stdout.readlines() is printed, [] is the output. In addition, if I add a print statement into the for loop, it never gets run. Could someone help me out here? Thanks!

推荐答案

您在阅读行之前关闭了连接:

You have closed the connection before reading lines:

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:从远程执行命令的标准输出中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:39