开发者

How to send EOF to stdin in paramiko?

I would like to execute some program through ssh and redirect its input from a file. The behaviour of the following code:

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

should be equivalent to (assuming public-key authentication)开发者_如何学C:

 ssh user@host cat < mumu

However the application hangs waiting for more input. I think this happens because the stdin stream is never closed. How do I do that?


Call shutdown() (or shutdown_write()) on the channel.


Call the method: channel.shutdown_write().


As I didn't use a channel explicitly I had to do it a bit differently. For whomever might find it helpful:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜