Having your shell commands run after consecutive ssh

I have a function in my zsh source file ~/.zshrc:

function cr() { ssh -p 5022 ssh servername2 screen -ls
}

However, everything after the first ssh seems to be executed after I close the ssh conection while I would like ssh servername2 to be executed into the ssh session. Similarly, the screen -ls is not executed inside servername2 but in my own local terminal after the first ssh closes.

Do you know how I could do that if you please? Please note that I indeed have a first ssh conection that allows me to connect to my wanted final server, servername2. I don't know why they do so in my lab or if it is frequent ^^' I know it is a sort of a gateway.

0

1 Answer

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
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like