Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/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 跨多个API调用保留SSH会话_Python_Python 3.x_Network Programming_Netmiko - Fatal编程技术网

Python 跨多个API调用保留SSH会话

Python 跨多个API调用保留SSH会话,python,python-3.x,network-programming,netmiko,Python,Python 3.x,Network Programming,Netmiko,这里的情况很有趣。目前,我有一个简单的FlaskAPI,它连接到后端的网络设备并检索命令输出 from netmiko import ConnectHandler def _execute_cli(self, opt, command): """ Internal method to create netmiko connection and execute command. """ try:

这里的情况很有趣。目前,我有一个简单的FlaskAPI,它连接到后端的网络设备并检索命令输出

from netmiko import ConnectHandler

def _execute_cli(self, opt, command):
        """
           Internal method to create netmiko connection and
           execute command.
        """
        try:
            net_connect = ConnectHandler(**opt)
            cli_output = (net_connect.send_command(command))
        except (NetMikoTimeoutException, NetMikoAuthenticationException,) as e:
            reason = e.message
            raise ValueError('Failed to execute cli on %s due to %s', opt['ip'], reason)
        except SSHException as e:
            reason = e.message
            raise ValueError('Failed to execute cli on %s due to %s', opt['ip'], reason)
        except Exception as e:
            reason = e.message
            raise ValueError('Failed to execute cli on %s due to %s', opt['ip'], reason)
        return cli_output


def disconnect(connection):
    connection.disconnect()
每个命令输出都在本地缓存一段时间。问题是,有人可能同时建立多个连接,而一个设备有一个连接限制(比如7)。如果调用过多,则会出现SSH连接问题,因为已达到最大连接数

我要做的是在一段指定的时间内(比如说5分钟),在这些API调用中为一个设备保留一个会话,这样我就不会填满设备上的连接


请告知。

好的,我不确定您所说的“在这些API调用中保留单个会话”是什么意思。但也许你可以做这样的事

每5分钟为所有设备及其用户量创建一个字典。例如:

self.users={device:0表示设备中的设备}

然后,无论何时调用
\u execute\u cli()
函数,您都可以在发送命令之前检查设备中的用户数量(在cisco中,命令为“show users”),并更新变量
self.users[device]=some\u number

因此,您可以简单地进行如下检查:

if self.users[device] < 7:
    try:
        net_connect = ConnectHandler(**opt)
        cli_output = (net_connect.send_command(command))
...
如果self.users[设备]<7:
尝试:
net_connect=ConnectHandler(**opt)
cli\u输出=(网络连接。发送\u命令(命令))
...