Paramiko Server: Signalling the client that stdout is closed

余生颓废 提交于 2019-12-13 00:51:10

问题


Trying to implement a test server in paramiko without having to modify the client for testing, I have stumbled across the problem how to close the stdout stream, making `stdout.read()´ not hang forever without going too low-level on the client's side. So far I have been able to communicate the completed command (simple text output to stdout) execution by:

class FakeCluster(paramiko.server.ServerInterface):
    def check_channel_exec_request(self,channel,command):
        writemessage = channel.makefile("w")
        writemessage.write("SOME COMMAND SUBMITTED")
        writemessage.channel.send_exit_status(0)
        return True

but I have not found a method to avoid the middle two lines in

_,stdout,_ = ssh.exec_command("<FILEPATH>")
    stdout.channel.recv_exit_status()
    stdout.channel.close()
    print(stdout.read())

which is already a good workaround not having to call channel.exec_command diretly (found here). Not closing the stdoutstream, my output will not print and the underlying transport on the server also remains active forever.

Closing the channel with stdout.channel.close() does not really have an effect and alternatively using os.close(writemessage.fileno()) (Difference explained here) does not work because the paramiko.channel.ChannelFile object used for the I/O streams "has no attribute 'fileno'". (Detailed explanation found here.)

Also, closing the channel directly on the server side throws a SSHException for the client..

Solutions proposed here do always modify the client side but I know from using my client script on the actual server that it must be possible without these additional lines!


回答1:


In check_channel_exec_request, close the channel on server side once exit status is sent, per protocol specification which states that a channel is active per lifetime of command executed and is closed there after.

This causes channel.eof() to be True on client side, indicating command has finished and reading from channel no longer hangs.

def check_channel_exec_request(self,channel,command):
    writemessage = channel.makefile("w")
    writemessage.write("SOME COMMAND SUBMITTED")
    writemessage.channel.send_exit_status(0)
    channel.close()
    return True

See this embedded server for integration testing based on paramiko that has been around for some years for reference - it implements exec requests among others. Speaking from experience, I would recommend instead using an embedded OpenSSH based server, an example of which can also be found on the same repository. Paramiko code is not particularly bug-free.



来源:https://stackoverflow.com/questions/47623800/paramiko-server-signalling-the-client-that-stdout-is-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!