Sample Header Ad - 728x90

How to chain ssh commands over multiple hops?

2 votes
1 answer
4280 views
Is it possible to chain multiple ssh connections together with each connection specified as an ssh host? I know it's possible to use the -W flag or nc to do a second hop to another hostname or ip address (see, e.g., https://unix.stackexchange.com/questions/25055/ssh-via-multiple-hosts) . I haven't been able to get this to work the way I want for a couple reasons. First, for the second hop, I want to use a key file stored on the intermediate host, and I don't see a way to specify this with either -W or nc. Second, the final destination has a variable ip address. To deal with this, I have a script running on the destination that writes its ip address to a file stored on the intermediate host and then a script (look_up_ip.sh) on the intermediate host that prints out this ip address. On the intermediate host, I have this entry in ~/.ssh/config: Host destination HostName destination User dest_user IdentityFile ~/.ssh/destination PreferredAuthentications publickey ProxyCommand nc $(look_up_ip.sh %h) %p which allows me to connect to the destination from the intermediate with just ssh destination. What I would like to do is put something in ~/.ssh/config on the first machine to define the destination host (as, e.g., hopped_destination) so that ssh will first connect to the intermediate host and then do ssh destination from there, so I can just do ssh hopped_destination from the first machine and have the intermediate ~/.ssh/config deal with the identity file and ip lookup for the destination. Part of the reason why I want this is that I ultimately want to be able to connect to the destination with VNC using vncviewer -via destination localhost:0, and I want the connection not to be accessible to other users on the intermediate host (as implied in parts of the accepted answer to this question: https://superuser.com/questions/96489/an-ssh-tunnel-via-multiple-hops) . I was hoping that it would be possible to put ssh into ProxyCommand on the first machine with something like: Host destination ProxyCommand ssh -t intermediate_user@intermediate_host ssh destination but I haven't found options that allow something like this to work. I would also welcome any suggestions on better ways to do this (is there a way to get rid of the nc ProxyCommand I am using now?). I could probably work out a script to do the VNC command more directly but that might be more complicated (handling the port forwarding directly and being sure to close things on exit, and being sure not to open a port for all users).
Asked by ws_e_c421 (539 rep)
Oct 26, 2016, 09:32 PM
Last activity: Jul 14, 2025, 01:09 PM