SSH via 3rd Machine

Local Computer (Fedora)  --SSH-->  Server1  --SSH-->  Server2

In some environments I work in, we have to use "jump boxes" where you ssh to one server in order to get to another server. Is there a quick way to do this, perhaps by editing ~/.ssh/config, such that whenever I ssh to Server2 from my local computer, it automatically creates the necessary connection to Server1? I can setup keys so that I'm not prompted for a password to Server1 if necessary.


This type of functionality was added into OpenSSH version 5.4 and can be used by doing

ssh -W server2 server1

Where server2 is your intended destination and server1 is your proxy host. You can make this easier by using the ProxyCommand option in your ssh config, something like:

host = *.example.com
user = packs
port = 22
ProxyCommand ssh -W %h:%p server1

I've also seen it done using netcat, so with the same examples as above

ssh server1 nc -q0 server2 22

Similarly, this can also be used in your ssh config, except replacing the ProxyCommand as

ProxyCommand ssh server1 nc -q0 %h %p

You can use a command like:

$ ssh -t user@server1 ssh user@server2

This command ssh you to the server2 via server1. You will be prompted for two passwords consecutively to login to server1 and then to server2. If you setup the needed SSH keys, you will should be logged in automatically to server2.

This is very useful when you can't login directly to server2.


I use forwarded ports:

# ~/.ssh/config

# The jumping-off point

Host server1
  Hostname blah.sample.com
  LocalForward 10002 server2:22
  LocalForward 10003 server3:22

# Servers behind the jumping-off point, reached by connecting
# to the forwarded ports above

Host server2
  HostKeyAlias server2
  Hostname localhost
  Port 10002

Host server3
  HostKeyAlias server3
  Hostname localhost
  Port 10003

This has several advantages over ssh -t user@server1 ssh user@server2:

  • Multiple sessions can be established through the same tunnel.
  • You only have to authenticate each connection once instead of twice.
  • Transparent use of ssh, scp and sftp (e.g., you can scp thisfile server2:~/thatfile without having to do any additional gymnastics).
  • X and port forwarding work without having to think about it.