How to know if a paramiko SSH channel is disconnected?

前端 未结 4 1467
闹比i
闹比i 2020-12-31 08:53

I\'m desinging test cases in which I use paramiko for SSH connections. Test cases usually contain paramiko.exec_command() calls which I have a wrapper for (call

相关标签:
4条回答
  • 2020-12-31 09:32

    My solution basically the same as yours, just organized differently:

    def connection(self):
        if not self.is_connected():
            self._ssh = paramiko.SSHClient()
            self._ssh.connect(self.server, self.port,
                              username = self.username, password = self.password)
    
        return self._ssh
    
    def is_connected(self):
        transport = self._ssh.get_transport() if self._ssh else None
        return transport and transport.is_active()
    
    def do_something(self):
        self.connection().exec_command('ls')
    
    0 讨论(0)
  • 2020-12-31 09:42

    In python, it's easier to ask for forgiveness than permission.

    Wrap each call to ssh.exec_command like so:

    try:
        ssh.exec_command('ls')
    except socket.error as e:
        # Crap, it's closed. Perhaps reopen and retry?
    
    0 讨论(0)
  • 2020-12-31 09:42

    I´ll just throw this here since someone might find it usefull. There is one catch with some of these methods. Paramiko internally uses sockets. Every new connection calls socket which opens a new file descriptor. Since processes are limited to certain number of open file descriptors after some time you will run out which will result in:

    socket.error: [Errno 24] Too many open files.

    So it is better to explicitly try to close the connection before establishing a new one using SSHClient.close() method.

    0 讨论(0)
  • 2020-12-31 09:42

    This works:

    import paramiko
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())        # Setting the missing host policy to auto add it
    client.connect('192.168.1.16', port=22, username='admin', password='admin', timeout=3, banner_timeout=2)
    
    channel = client.invoke_shell()                 # Request an interactive shell session on this channel. If the server allows it, the channel will then be directly connected to the stdin, stdout, and stderr of the shell.
    print channel.closed          # False
    command = 'reboot'
    channel.send(command + '\n')
    # wait a while
    print channel.closed          # True
    
    0 讨论(0)
提交回复
热议问题