如何将EOF发送到paramiko的stdin?

问题描述 投票:4回答:3

我想通过ssh执行一些程序并从文件中重定向其输入。以下代码的行为:

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流永远不会关闭。我怎么做?

python stdin eof paramiko
3个回答
5
投票

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


4
投票

调用方法:channel.shutdown_write()


0
投票

因为我没有明确地使用频道,所以我必须做一些不同的事情。对于任何可能发现它有帮助的人:

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())
© www.soinside.com 2019 - 2024. All rights reserved.