Repository navigation
Description
Are you using paramiko as a client or server?
Client
What feature(s) aren't working right?
SSH
What version(s) of paramiko are you using?
4.0.0
What version(s) of Python are you using?
3.13.12
What operating system and version are you using?
Debian unstable
If you're connecting as a client, which SSH server are you connecting to?
tunnelled via SSH to Apache MINA SSHD
If you're using paramiko as part of another tool, which tool/version?
No response
Expected/desired behavior
Hey.
This is probably a tough one:
I have a class which encapsulates a paramiko SSHClient, basically like that:
import threading
import paramiko
class SSH:
def __init__(self):
self.connect_lock = threading.Lock()
self.ssh_client = paramiko.client.SSHClient()
self.ssh_client.set_missing_host_key_policy(paramiko.client.RejectPolicy)
#load trusted host keys
...
#establish the initial connection
try:
self._connect()
except Exception as e:
log.warning(f"Failed to initially establish the SSH connection: {e}", exc_info=e)
def _connect(self):
with self.connect_lock:
#(re-)connect the SSH client if necessary
transport = self.ssh_client.get_transport()
if transport is None or not transport.is_authenticated():
#close any previous connection
self.ssh_client.close()
#connect to the SSH server
self.ssh_client.connect(hostname=cfg.admin_ssh_host, port=cfg.admin_ssh_port, username=cfg.admin_ssh_user,
password=cfg.admin_ssh_passphrase, key_filename=cfg.admin_ssh_private_key, passphrase=cfg.admin_ssh_private_key_passphrase,
look_for_keys=not cfg.admin_ssh_no_default_private_key_locations, allow_agent=not cfg.admin_ssh_no_agent,
timeout=cfg.admin_ssh_tcp_timeout, banner_timeout=cfg.admin_ssh_banner_timeout, auth_timeout=cfg.admin_ssh_authentication_timeout, channel_timeout=cfg.admin_ssh_channel_open_timeout
)
if cfg.admin_ssh_keepalive_interval is not None:
transport = self.ssh_client.get_transport()
transport.set_keepalive(cfg.admin_ssh_keepalive_interval)
def execute_command(self, command, *, strip_trailing_empty_lines=True, split_lines=False, retries=1):
for i in range(1 + retries):
try:
(stdin, stdout, stderr) = self.ssh_client.exec_command(command, timeout=cfg.admin_ssh_command_channel_timeout)
stdin.close()
stdout_data = stdout.read().decode()
stderr_data = stderr.read().decode()
exit_status = stdout.channel.recv_exit_status()
except Exception as e1:
if i < retries:
log.warning(f"Failed to execute the command `{command}` via the SSH interface of the dCache `admin` service (try {i+1} of {1+retries}): {e1}", exc_info=e1)
#re-establish the connection
try:
self._connect()
except Exception as e2:
log.warning(f"Failed to re-establish the SSH connection: {e2}", exc_info=e2)
#re-try executing the command in the loop’s next iteration
else:
log.error(f"Failed to execute the command `{command}` via the SSH interface of the dCache `admin` service (try {i+1} of {1+retries}): {e1}", exc_info=e1)
#don’t re-try executing the command
return None
if stderr_data or exit_status != 0:
if stderr_data and exit_status == 0:
log.error(f"The dCache admin command `{command}` terminated with the exit status `0` but produced output on standard error and is thus considered to have failed.")
elif not stderr_data and exit_status != 0:
log.error(f"The dCache admin command `{command}` failed with the exit status `{exit_status}`.")
else:
log.error(f"The dCache admin command `{command}` produced output on standard error and failed with the exit status `{exit_status}`.")
return None
if strip_trailing_empty_lines:
while stdout_data.endswith("\r\n"):
stdout_data = stdout_data.removesuffix("\r\n")
if split_lines:
return stdout_data.split("\r\n")
else:
return stdout_dataSimply said, it does initial configuration in __init__ and also actually connects there already.
When executing a command via its execute_command, it simply tries to do so via SSHClient.exec_command, and if that gives an exception, it tries to re-connect (because the connection might broken off meanwhile, and then (via the for-loop) tries to re-execute the command.
Both only once (per default).
When it calls it's _connect it first does SSHClient.close() so the transport/etc. should be gone.
For testing, I set up a (Open)SSH tunnel to a remote host, where the actual SSH server where the my SSH object connects to runs,... that allows me to easily interrupt the connection, simply by closing that forward (and restarting it again).
Now if I'm single threaded, things work like this:
- I open the port forwarding
- start my program
- the program executes a first
exec_command, works - the program goes into a
sleep()and I kill the forward and restart it (via a newssh -L …) - the program continues, but a second
exec_commandfails with aSSH session not active. - the program does the reconnect, that works, it re-tries the second
exec_commandthat previously failed, also works
But when I go multi-threaded (the first command from above, stays a single one, with only one thread, but the second is now replaced with many concurrent commands via concurrent.futures with threads) it starts to see issues:
First, I needed to add the connect_lock mutex around my connect.
AFAIU, Paramiko is meant to be thread safe? But it doesn't seem to be when connecting.
Without the mutex, when the program continues after the sleep() at step 5, all the threads would have tried their exec_command, all would have failed (which is still fine) all would have tried to reconnect and most of them would have seen if transport is None or not transport.is_authenticated(): which is True for them and thus actually did the re-connect.
That fails miserably if done by many threads... always with different exceptions.
Not sure whether this part is expected to be thread safe or not, though.
But the mutex fixes this part, so fine for me.
However there's a 2nd problem and I can't find a cause for it. I repeat the above now with the 2nd commands being many concurrent:
- I open the port forwarding
- start my program
- the program executes a first
exec_command, works - the program goes into a
sleep()and I kill the forward and restart it (via a newssh -L …) - the program continues, but now it starts many concurrent
exec_command, these all fail (because the connection was interrupted) - each thread does the reconnect, but only the first one gets the mutex, so all others wait for now
- the one who got the mutex now times out a the
self.ssh_client.connect(...)even if I very long timeouts) - it logs the warning, but my program then still tries to re-execute the command in the next iteration of the
for... I could of course prevent, this but it's not really the problem IMO anyway - no more tries left (I use
retries=1), so that one command of the many finally fails with an error - a next thread gets the lock, for it the
if transport is None or not transport.is_authenticated():is alsoTrue, it tries to re-connect, this time it works, and all subsequent commands are properly executed.
It's always the first re-connect that fails, and always the 2nd that works.
Now despite (8) (the reconnection, which did a close() initially) having failed, exec_command still even tries (despite the SSHClient should already know that it has no transport??) and it eventually times out depending on cfg.admin_ssh_command_channel_timeout, even if I set a very long one).
But the main question is IMO, why does (8) fail the first time but work the 2nd?
I tried to:
- completely stopped/restarted the remote SSH server, while my program still sleeps... because I thought maybe it somehow has kept the old connection still open, confuses the new one for the old and only then kills of the old but also doesn't allow the (first) new
With really shutting the remote server completely down and restarting it between the tries... this shouldn't be able to be the cause, right? Because of that I rather don't thing the issue is in Apache MINA SSHD. - created a complete new
SSHClientobject at the re-connect... just in case the.close()didn't close everything properly - tried with disallowing SSH agents... (merely because some bug reports here at paramiko said that might help)
None worked. So I don't get what else could be special about the first re-connection.
Any ideas would be appreciated.
My workaround now is, that I simply try a 2nd reconnect if the first fails.
Cheers,
Chris.
Actual behavior
see above
How to reproduce
No response
Anything else?
No response
Activity
calestyo commentedon May 1, 2026
Maybe it is somehow related to Apache MINA SSHD (though I still don't understand how it could be)...
I repeated the above procedure except that my port forwarding doesn't point to Apache MINA SSHD, but again to OpenSSH on the remote host.
As executed commands I used some shell commands like echo or so.
Apart from that, the same.
I don't get a failure at the re-connection (after my interruption) anymore... but instead many of the
exec_commandstill fail, now with:I assume however this might be simply some rate limiting or so done by Open
sshdbecause myconcurrent.futures.ThreadPoolExecutor(max_workers=1024)had quite a few workers O:-)If I reduce those drastically (to
5), then withsshdit runs through.The same trick doesn’t help anything with Apache MINA SSHD. With that it's still always the first re-connect that fails.
(btw: with
sshdit was always different ones of the concurrent commands, that failed)