如何在paramiko中向stdin发送EOF?

6
我希望通过ssh执行一些程序,并将其输入重定向到文件。以下代码的行为是:
```bash ssh user@host 'program < file' ```
这将在远程主机上启动名为“program”的程序,并从名为“file”的文件中读取输入。
channel.exec_command('cat')
with open('mumu', 'r') as f:
    text = f.read()
    nbytes = 0
    while nbytes < len(text):
        sent = channel.send(text[nbytes:])
        if sent == 0:
            break
        nbytes += sent

应该等同于(假设使用公钥身份验证):
 ssh user@host cat < mumu

然而,应用程序会挂起并等待更多输入。我认为这是因为stdin流从未关闭。我该怎么做?

3个回答

5

在通道上调用shutdown()(或shutdown_write())。


那么stdout和stderr会发生什么? - Alexandru

4
调用方法:channel.shutdown_write()

1

由于我没有明确使用频道,所以我必须以稍微不同的方式进行操作。对于可能会发现此方法有用的人:

client = paramiko.SSHClient()
connection = client.connect(hostname)
stdin, stdout, stderr = connection.exec_command('cat')
stdin.write('spam')
# Close the channel, this results in an EOF for `cat`.
stdin.channel.shutdown_write()
# stdout/stderr are readable.
print(stdout.read().decode())
print(stderr.read().decode())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接