使用 Paramiko 的标准输出作为标准输入与子进程 [英] Use Paramiko's stdout as stdin with subprocess

查看:59
本文介绍了使用 Paramiko 的标准输出作为标准输入与子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Python 在远程服务器上执行命令并将标准输出通过管道传输到本地命令?做ssh 主机'echo test' |python中的cat,我试过了

How can I execute a command on a remote server in Python and pipe the stdout to a local command? To do ssh host 'echo test' | cat in Python, I have tried

import paramiko
import subprocess

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('host', username='user')
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('echo test')
proc = subprocess.Popen(['cat'], stdin=ssh_stdout)
outs, errs = proc.communicate()
print(outs)

但我得到异常 'ChannelFile' 对象没有属性 'fileno'.看来Paramiko的ssh_stdout不能用作subprocess.Popen的stdin.

but I get the exception 'ChannelFile' object has no attribute 'fileno'. It seems that Paramiko's ssh_stdout can't be used as stdin with subprocess.Popen.

推荐答案

是的,subprocess 无法重定向假"文件的输出.它需要 fileno ,它只用真实"文件定义(io.BytesIO() 也没有).

Yes, subprocess cannot redirect output on a "fake" file. It needs fileno which is defined only with "real" files (io.BytesIO() doesn't have it either).

我会像下面的代码演示一样手动完成:

I would do it manually like the following code demonstrates:

proc = subprocess.Popen(['cat'], stdin=subprocess.PIPE)
proc.stdin.write(ssh_stdout.read())
proc.stdin.close()

所以你告诉 Popen 输入是一个 pipe,然后你在管道中写入 ssh 输出数据(并关闭它所以 cat 知道什么时候必须结束)

so you're telling Popen that the input is a pipe, and then you write ssh output data in the pipe (and close it so cat knows when it must end)

这篇关于使用 Paramiko 的标准输出作为标准输入与子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆