However, everything after the first ssh seems to be executed after I close the ssh connexion
That's because functions (and scripts, and aliases) do not simulate keyboard input. Each statement is a command that must finish before the next is run, and the entire thing runs in the context of the parent shell.
(This applies regardless of how the commands are separated; whether it's new lines, or ;
or &&
as separator, they all will be run locally and not sent as "fake keyboard input".)
One way to make this work can be found in older posts – the second ssh
has to be given to the first one as a "remote command":
In many cases, there is a better option to connect through intermediate hosts using SSH's "tunnel" or "jumphost" support:
ssh -J ssh.mylaboratory.fr servername2 "screen -ls"
I would also suggest defining SSH parameters in ~/.ssh/config
so that they don't need to be repeated for every SSH or SFTP or sshfs invocation:
Host ssh.mylaboratory.fr
User myname
Port 5022
Or possibly even:
Host lab
Hostname ssh.mylaboratory.fr
User myname
Port 5022
This would let you simplify the first command to ssh ssh.mylaboratory.fr
or ssh lab
, or the "jump" command to ssh -J lab server2
.
Similarly, if the ssh -J
option works (i.e. it wasn't explicitly disabled by the remote server), you can define that in the config as well, allowing you to directly use ssh server2
and even sshfs server2:[...]
:
Host server2
ProxyJump lab