首页 > 解决方案 > 保持多个 ssh 连接处于活动状态并在下一次函数调用时使用正确的连接

问题描述

我正在创建一个测试环境,其中多个命令在短时间内发送到多个设备。测试的设备有 5 个同时 ssh 连接的限制。在当前代码中,每次发送新命令时都会打开一个新的 ssh 连接。不直接关闭连接,ssh_client.close它需要很长时间才能关闭(似乎需要几分钟),这使得设备在发送 5 个命令后无法访问。我的想法是每次都跳过关闭连接并保持打开状态,直到下次调用该函数时检查特定的 IP 连接是否打开,如果没有打开它。

ssh_client.connect如果没有触发,如果它已经打开,函数如何知道使用正确的连接?

def SSHConnection(ip,command):
     name="admin"
     password="admin"

     try:
        paramiko.util.log_to_file("paramiko_SSH.log")
        ssh_client = paramiko.SSHClient()
        
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname=ip,username=name,password=password,timeout=1)

        remote_connection = ssh_client.invoke_shell()
        remote_connection.send(command)
        remote_connection.send('\r\n')

        output = remote_connection.recv(10240)

        ssh_client.close
        return output

      except:
        return "Connection failed"


# Function call is triggered multiple times for each unit and sends commands to test the devices
# The devices have a limit of 5 simultaneously ssh connections which will be exceeded and no more commands can be sent until the ssh connections are closed.

SSHConnection(ip,command)

标签: pythonsshparamiko

解决方案


推荐阅读