如何在paramiko中写入stdin(从exec_command返回)?

Mar*_* C. 3 python unix paramiko ssh-tunnel

我试图用paramiko写入自定义程序的stdin。这是一个最小的(非工作)示例:

〜/ stdin_to_file.py:

#! /usr/bin/python

import time, sys
f = open('/home/me/LOG','w')
while True:
    sys.stdin.flush()
    data = sys.stdin.read()
    f.write(data+'\n\n')
    f.flush()
    time.sleep(0.01)
Run Code Online (Sandbox Code Playgroud)

然后,我在IPython中执行以下命令:

import paramiko
s = paramiko.client.SSHClient 
s.load_system_host_keys()
s.connect('myserver')
stdin, stdout, stderr = s.exec_command('/home/me/stdin_to_file.py')
stdin.write('Hello!')
stdin.flush()
Run Code Online (Sandbox Code Playgroud)

不幸的是,〜/ LOG中什么也没有出现。但是,如果我这样做

$ ~/stdin_to_file.py < some_other_file
Run Code Online (Sandbox Code Playgroud)

some_other_file的内容显示在〜/ LOG中。

谁能建议我哪里出问题了?看来我在做合乎逻辑的事情。这些都不起作用:

stdin.channel.send('hi')
using the get_pty parameter
sending the output of cat - to stdin_to_file.py
Run Code Online (Sandbox Code Playgroud)

pyn*_*exj 7

sys.stdin.read()会一直读到EOF,所以在您的paramiko脚本中,您需要关闭stdin(从返回exec_command())。但是如何?

1. stdin.close()不会工作。

根据Paramiko的文档(v1.16):

警告:要正确模拟通过套接字的makefile()方法创建的文件对象,a Channel及其及其ChannelFile应该能够独立关闭或进行垃圾回收。目前,关闭ChannelFile不只是刷新缓冲区。

2。 stdin.channel.close() also has problem.

由于stdinstdoutstderr都共享一个通道,stdin.channel.close()因此也会关闭stdoutstderr(这是不希望的)。

3。 stdin.channel.shutdown_write()

正确的解决办法是使用stdin.channel.shutdown_write()它不允许写通道,但仍允许从通道读取,从而stdout.read()stderr.read()仍然坚持工作。


见下面的例子来看看之间的区别stdin.channel.close()stdin.channel.shutdown_write()

[STEP 101] # cat foo.py
import paramiko, sys, time

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy() )
ssh.connect(hostname='127.0.0.1', username='root', password='password')
cmd = "sh -c 'read v; sleep 1; echo $v'"
stdin, stdout, stderr = ssh.exec_command(cmd)
if sys.argv[1] == 'close':
    stdin.write('hello world\n')
    stdin.flush()
    stdin.channel.close()
elif sys.argv[1] == 'shutdown_write':
    stdin.channel.send('hello world\n')
    stdin.channel.shutdown_write()
else:
    raise Exception()
sys.stdout.write(stdout.read() )
[STEP 102] # python foo.py close           # It outputs nothing.
[STEP 103] # python foo.py shutdown_write  # This works fine.
hello world
[STEP 104] #
Run Code Online (Sandbox Code Playgroud)