python - 如何使用 python 结构发送流

标签 python ssh stream fabric paramiko

我需要通过网络将程序的标准输出流发送到在另一台主机上运行的另一个程序的标准输入。

这可以使用 ssh 轻松完成:

program 1 | ssh host 'program 2'

使用 subprocess 调用它很简单:
subprocess.call("program 1 | ssh host 'program 2'", shell=True)

但是,由于我需要在远程主机上运行许多其他命令,所以我使用 fabric .

用织物发送文件很容易,但我找不到任何关于发送流的文档。我知道fabric 使用paramiko ssh 库,所以我可以use it's channel但似乎没有从结构访问 channel 的文档。

最佳答案

我最终挖掘了织物源代码( fabric.operations._execute )并得出了这个:

from fabric.state import default_channel
import subprocess

def remote_pipe(local_command, remote_command, buf_size=1024):
    '''executes a local command and a remove command (with fabric), and 
    sends the local's stdout to the remote's stdin.
    based on fabric.operations._execute'''
    local_p= subprocess.Popen(local_command, shell=True, stdout=subprocess.PIPE)
    channel= default_channel() #fabric function
    channel.set_combine_stderr(True)
    channel.exec_command( remote_command )
    read_bytes= local_p.stdout.read(buf_size)
    while read_bytes:
        channel.sendall(read_bytes)
        read_bytes= local_p.stdout.read(buf_size)
    local_ret= local_p.wait()
    channel.shutdown_write()
    received= channel.recv(640*1024) #ought to be enough for everyone
    remote_ret= channel.recv_exit_status()
    if local_ret!=0 or remote_ret!=0:
        raise Exception("remote_pipe failed: "+received)

关于python - 如何使用 python 结构发送流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19596920/

相关文章:

python - Pytest 警告 : Module already imported so cannot be rewritten: pytest_remotedata

python - python脚本中的身份验证以root身份运行

amazon-web-services - SSH 登录 AWS EC2 错误 : packet_write_wait: Connection to x. x.x.x 端口 22:管道损坏

git - SSH 主机真实性检查期间 "[fingerprint]"选项的目的是什么?

python - 将 Netcat 流写入带有附加文本的文件

javascript - Node.js HTTP 模块 : Response + Request

python - 在html页面中使用re模块搜索字符串

python - 如何通过相等的索引和列名将空数据框与另一个填充的数据框合并/连接?

ssh localhost 连接被 127.0.0.1 关闭?

java - 如何在 Java 8 中使用流将集合/数组转换为 JSONArray