6

我想通过 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

但是应用程序挂起等待更多输入。我认为这是因为标准输入流永远不会关闭。我怎么做?

4

3 回答 3

5

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

于 2010-03-31T15:52:31.067 回答
4

调用方法:channel.shutdown_write().

于 2010-06-22T12:41:31.747 回答
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())
于 2019-03-15T10:44:18.960 回答