Python 使用 Paramiko 一次创建多个 SSH 连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3485428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating multiple SSH connections at a time using Paramiko
提问by Whit3H0rse
The code below runs grep in one machine through SSH and prints the results:
下面的代码通过 SSH 在一台机器上运行 grep 并打印结果:
import sys, os, string
import paramiko
cmd = "grep -h 'king' /opt/data/horror_20100810*"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.10.3.10', username='xy', password='xy')
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('xy\n')
stdin.flush()
print stdout.readlines()
How can I grep five machines all at once (so that I don't have major delay), than put all that in five variables and print them all out.
我怎样才能一次 grep 五台机器(这样我就不会有重大延迟),而不是将所有这些都放在五个变量中并将它们全部打印出来。
采纳答案by Alex Martelli
You'll need to put the calls into separate threads (or processes, but that would be overkill) which in turn requires the code to be in a function (which is a good idea anyway: don't have substantial code at a module's top level).
您需要将调用放入单独的线程(或进程,但这会矫枉过正),这反过来又要求代码位于函数中(无论如何这是一个好主意:在模块顶部没有大量代码等级)。
For example:
例如:
import sys, os, string, threading
import paramiko
cmd = "grep -h 'king' /opt/data/horror_20100810*"
outlock = threading.Lock()
def workon(host):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username='xy', password='xy')
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('xy\n')
stdin.flush()
with outlock:
print stdout.readlines()
def main():
hosts = ['10.10.3.10', '10.10.4.12', '10.10.2.15', ] # etc
threads = []
for h in hosts:
t = threading.Thread(target=workon, args=(h,))
t.start()
threads.append(t)
for t in threads:
t.join()
main()
If you had many more than five hosts, I would recommend using instead a "thread pool" architecture and a queue of work units. But, for just five, it's simpler to stick to the "dedicated thread" model (especially since there is no thread pool in the standard library, so you'd need a third party package like threadpool... or a lot of subtle custom code of your own of course;-).
如果您有五个以上的主机,我建议您改用“线程池”架构和工作单元队列。但是,对于短短五年,这是简单的坚持走“专用线”模式(尤其是因为在标准库中没有线程池,所以你需要一个第三方软件包像线程池......还是有很多微妙的习俗当然你自己的代码;-)。
回答by Rushi Agrawal
Just run everything in a forloop, and don't forget to close stdin before moving on to next iteration. That is, after line stdin.flush()add line stdin.close()
只需在for循环中运行所有内容,并且在进行下一次迭代之前不要忘记关闭标准输入。即行后stdin.flush()加行stdin.close()

