如何在paramiko中向stdin发送EOF?

6 投票
3 回答
3748 浏览
提问于 2025-04-15 21:05

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

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())
4

调用这个方法:channel.shutdown_write()

5

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

撰写回答