当前位置: 首页 > 面试题库 >

使用Paramiko一次创建多个SSH连接

滑景胜
2023-03-14
问题内容

下面的代码通过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()

我如何一次将5台机器全部置入grep(这样就不会造成重大延迟),而不是将所有这些都放入5个变量中并全部打印出来。


问题答案:

您需要将调用放在单独的线程(或进程中,但这可能会过大),这反过来又要求代码位于函数中(无论如何,这是一个好主意:模块的顶部没有大量代码水平)。

例如:

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




 类似资料:
  • 问题内容: 我正在学习python。我需要使用隧道创建者来从数据库中读取信息并关闭隧道。我使用paramiko,但是我没有使用tonelem示例。请举一个创建隧道的简单代码示例。 提前致谢! 问题答案: 在工作中,我们通常创建ssh隧道转发端口。我们的方法是使用标准命令,使子进程在单独的线程中运行。我找到了这个有用的链接:https : //github.com/paramiko/paramiko

  • 问题内容: 我正在使用Paramiko通过ssh连接到服务器。 基本身份验证效果很好,但我不明白如何使用公钥进行连接。 当我连接腻子时,服务器告诉我这一点: 我用这个ppk文件连接到它: 使用基本身份验证,我从日志中得到的错误是: 我尝试包含该ppk文件并将其设置为auth_public_key,但是没有用。 你能帮助我吗? 问题答案: 好的@Adam和@Kimvais是正确的,paramiko无

  • 考虑这个例子 我有一个函数,它以作为输入,并返回三个值,我想存储到三个不同的变量。下面的似乎工作正确 然而,当我试图创建相应的变量时,我得到了一个错误 你怎么认为? 我曾经在pandas apply()的返回多列中使用伟大的解决方案,但在当前的pandas中,此解决方案不再有效 谢谢!

  • 问题内容: 我需要一次创建多个表。我很难找出正确的方法来完成此任务。目前,我的脚本如下所示: 显然,这是行不通的,并且不会创建任何表。有一种简单的方法可以一次创建多个表吗? 问题答案: MySQL变得令人困惑,因为您没有划定查询范围。在第一条语句后添加分号: 另外,根据Heredoc文档,请确保位于行的开头, 没有其他字符,除了分号外 。 鉴于上述方法似乎无效,请尝试以下代码: 您 可以 使用(M

  • 问题内容: 我是python新手。我写了一个脚本来连接到主机并执行一个命令 当远程命令不需要tty时,可以正常工作。我找到了一个与Paramiko的invoke_shell示例嵌套SSH会话。我对这种解决方案不满意,因为如果服务器上的提示未在我的脚本中指定->无限循环,或者脚本中指定的提示是返回文本中的字符串->不会接收到所有数据。有没有更好的解决方案,也许将stdout和stderr像我的脚本一

  • 我是Python的新手。我编写了一个脚本连接到主机并执行一个命令