使用 Paramiko 一次创建多个 SSH 连接 [英] Creating multiple SSH connections at a time using Paramiko

查看:125
本文介绍了使用 Paramiko 一次创建多个 SSH 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码通过SSH在一台机器上运行grep并打印结果:

The code below runs grep in one machine through SSH and prints the results:

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()

我怎样才能一次 grep 五台机器(这样我不会有重大延迟),而不是将所有这些放入五个变量中并将它们全部打印出来.

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.

推荐答案

您需要将调用放入单独的线程(或进程,但那会矫枉过正),而这又要求代码位于函数中(无论如何,这是个好主意:在模块的顶层不要有大量代码).

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).

例如:

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;-).

这篇关于使用 Paramiko 一次创建多个 SSH 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆