开发者

How to send EOF to stdin in paramiko?

开发者 https://www.devze.com 2022-12-25 20:05 出处:网络
I would like to execute some program through ssh and redirect its input from a file. The behaviour of the following code:

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

精彩评论

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