ssh阻塞与非阻塞mod的区别

2024-05-16 21:05:31 发布

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

这个问题听起来很愚蠢,因为每个使用SSH库的开发人员都应该问自己这个问题(?)。但是我真的找不到阻塞和非阻塞之间的区别。。。在

我是说好吧。。。一个阻塞直到它收到答案,另一个发送查询并立即返回,然后你自己检查回复缓冲区。。。我有那个角色。在

但是为什么要用一个而不是另一个呢?我找不到答案。。。 是关于表演吗?如果有区别,为什么?在

提前感谢您对这些问题的回答。在

——编辑:忘了下面的“奖金问题”,我终于编好了非阻塞模式,也遇到了同样的问题,一定是libssh2的问题。所以我还是没有得到非阻塞模式的附加值。。。---在

Bonus question:
I'm not really sure could this difference explain something I'm experiencing?
I have a python script which connects to many hosts to run several commands.
It was using paramiko library in non-blocking mode. Paramiko is pure python and really slow for establishing ssh connections to many hosts...
I'm changing it for pylibssh2 which is python bindings for the C library libssh2. Since I didn't get the difference, I started to code in blocking mode.

Results:
- libss2 is much faster than paramiko (connection to 230 hosts in parallel in 4s instead of 1m30s)
- For running commands successively, libssh2 is also faster.
- When I run commands through ssh from several parallel threads, the code with libssh2 in blocking mode becomes slowlier than paramiko in non-blocking mode.
- I also noticed that the CPU consumption is very low compared with previous version. I guess part of this is related to C vs python but it seems than beyond the SSH API, my script itself performs less actions. Are threads blocking each other when sending commands through SSH in blocking mode?


Tags: theto答案inparamikoforismode
1条回答
网友
1楼 · 发布于 2024-05-16 21:05:31

原因是,如果你想同时做两件事,比如从其他网络连接读取,和你的SSH会话,你有两个选择:

  • 使用阻塞API,并使用两个线程或进程,这样您就可以同时执行它们

  • 使用非阻塞API,这样同一个线程就可以同时完成这两个任务

后一种方法称为Asynchronous I/O。例如,请参见广泛使用它的twisted。在

相关问题 更多 >