如何在paramiko中将EOF发送到stdin?

2024-09-29 17:09:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

应等效于(假设公钥身份验证):

^{pr2}$

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


Tags: 文件代码text程序withchannelopenssh
3条回答

在通道上调用^{}(或shutdown_write())。在

调用方法:channel.shutdown_write()。在

因为我没有明确地使用频道,所以我不得不做一些不同的事情。对于任何可能觉得有用的人:

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

相关问题 更多 >

    热门问题