gpt4 book ai didi

python - Paramiko 服务器 : Signalling the client that stdout is closed

转载 作者:行者123 更新时间:2023-12-04 16:08:17 30 4
gpt4 key购买 nike

尝试在paramiko中实现测试服务器无需修改客户端进行测试,我偶然发现了如何关闭 stdout 流的问题,使 `stdout.read()` 不会永远挂起,而不会在客户端太低级别。到目前为止,我已经能够通过以下方式传达完成的命令(简单文本输出到标准输出)执行:

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

但是我还没有找到避开中间两行的方法

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

这已经是一个很好的解决方法,不必直接调用 channel.exec_command(找到 here)。不关闭 stdout 流,我的输出将不会打印,服务器上的底层传输也永远保持事件状态。

使用 stdout.channel.close() 关闭 channel 并没有真正的效果,或者使用 os.close(writemessage.fileno()) (区别解释here ) 不起作用,因为用于 I/O 流的 paramiko.channel.ChannelFile 对象“没有属性‘fileno’”。 (详细解释见here。)

此外,直接在服务器端关闭 channel 会为客户端抛出 SSHException..

提出的解决方案here一定要修改客户端,但我知道在实际服务器上使用我的客户端脚本,没有这些额外的行一定是可能的!

最佳答案

check_channel_exec_request 中,一旦发送退出状态,就关闭服务器端的 channel ,根据协议(protocol)规范,该规范规定 channel 在命令执行的整个生命周期内处于事件状态,并在此之后关闭。

这会导致客户端的 channel.eof()True,表示命令已完成并且从 channel 读取不再挂起。

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

查看此 embedded server for integration testing基于已经存在多年以供引用的 paramiko - 它实现了 exec 请求等。根据经验,我建议使用基于嵌入式 OpenSSH 的服务器,example of which can also be found on the same repository . Paramiko 代码并不是特别没有错误。

关于python - Paramiko 服务器 : Signalling the client that stdout is closed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47623800/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com