Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 保持多个ssh连接处于活动状态,并在下次函数调用时使用正确的连接_Python_Ssh_Paramiko - Fatal编程技术网

Python 保持多个ssh连接处于活动状态,并在下次函数调用时使用正确的连接

Python 保持多个ssh连接处于活动状态,并在下次函数调用时使用正确的连接,python,ssh,paramiko,Python,Ssh,Paramiko,我正在创建一个测试环境,其中多个命令在短时间内发送到多个设备。 测试的设备限制为5个ssh连接。在当前代码中,每次发送新命令时都会打开一个新的ssh连接。 ssh\u client.close不会直接关闭连接,它需要很长时间才能关闭(似乎需要几分钟),这使得发送5个命令后无法访问设备。 我的想法是跳过每次关闭连接,并在下次调用函数时保持连接打开,只需检查特定的IP连接是否打开,如果没有,则打开它 如果未触发ssh\u client.connect,函数如何知道使用已打开的正确连接 def SSH

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

如果未触发
ssh\u 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)

您想保持会话打开,而不必关闭会话

如何实现tmux会话来运行部分脚本

不一定是正确的语法,只是我将如何实现它


PS:不一定是你想要的,但它可以工作

谢谢你的建议,我从未听说过tmux。我不确定它是否能在我的情况下工作,但我会仔细研究它。如果能够捕获基于IP的远程连接变量,那就太好了。=)这可能不是最好的解决方案,但我找到了一个cli命令来终止测试设备上的所有ssh连接,因此在我发送了一个命令并收到所需的信息后,我会发送第二个命令来终止远程设备上的所有ssh会话。您尝试过吗?没有,我没有时间尝试。我现在开始工作了,所以我不得不继续做其他的工作。无论如何,谢谢你。
os.system('tmux new -s client_1')
opensockets.py    
os.system('tmux detach')