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
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')
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?
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.
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