如何将EOF发送到paramiko的stdin?

时间:2010-03-31 15:36:01

标签: python stdin eof paramiko

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

3 个答案:

答案 0 :(得分:5)

在频道上呼叫shutdown()(或shutdown_write())。

答案 1 :(得分:4)

调用方法:channel.shutdown_write()

答案 2 :(得分: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())