I often need to connect to a server with ssh from another server because I don’t have direct access. I even gave a small configuration example to use such jump hosts using ProxyCommand s.

A while ago, I got fed up to have to add new entries for each host I wanted to join with a jump server, especially when I only need these entries sporadicly, and decided to write a generic configuration. I ended up with this setup:

Host *%* ProxyCommand ssh $(echo %h | cut -d%% -f1) nc -w1 $(echo %h | cut -d%% -f2) %p

The trick here is that you can use subshell expansions in a ProxyCommand . So, when I ssh to “host1%host2”, the first subshell expansion returns “host1” and the second “host2”, this setup ends up being the equivalent of :

Host host1%host2 ProxyCommand ssh host1 nc -w1 host2 %p

which is quite similar to the setup from my previous post.

Later on, I came up with an even more powerful implementation:

Host *%* ProxyCommand ssh $(echo %h | awk -F%% '{OFS="%%"; NF--; print $0}') nc $(echo %h | awk -F%% '{print $NF}') %p

Here, the first awk splits at the % characters and returns all fields except the last one, and the second awk returns only the last field. As a consequence, ssh ing to “host1%host2%host3%host4” will have the first subshell expansion return “host1%host2%host3” and the second “host4”. The setup will then be equivalent to:

Host host1%host2%host3%host4 ProxyCommand ssh host1%host2%host3 nc -w1 host4 %p

The ssh in the ProxyCommand will, in turn, trigger the rule again so that the result is that host4 will be contacted from host3, which is contacted from host2 that we contacted from host1.

In the meanwhile, I decided % was not that nice a separator, and switched to using /, which also allows for a nicer setup with the same recursive effect:

Host */* ProxyCommand ssh $(dirname %h) nc -w1 $(basename %h) %p

Finally, since some remote hosts don’t have nc installed, I usually copy it in my $HOME on these servers and changed my setup to:

Host */* ProxyCommand ssh $(dirname %h) PATH=.:\$PATH nc -w1 $(basename %h) %p

The main drawback of this method is that the more jump hosts you use, the more your ssh traffic is encapsulated (recursively) in other ssh traffic. The advantage, though, is that you don’t need to forward an agent onto untrusted servers to use ssh key authentication on any of the jump or final servers, nor to forward X11 or tunnel multiple times.

p.d.o

Both comments and pings are currently closed.