How to ssh to a server which I can not directly reach?

Solution 1:

You can use the following command to set up an SSH tunnel from the remote server to your local machine:

$ ssh -f -N -R 1234:localhost:22 [email protected]_machine_ip

When the tunnel is set up, you can simply ssh to your remote server using the following command:

$ ssh -p 1234 [email protected]

Please note that you need to set up ssh keys for automatic login (no password prompt). If you want to create the SSH tunnel interactively, you can remove the options -f -N. For more info, man ssh.

Solution 2:

If you are running a newer version of OpenSSH (7.3+) then you can use ProxyJump which bakes everything together magically:

ssh -J windows_machine remote_server

Which in your ~/.ssh/config looks like:

Host remote_server
        HostName remote_server
        ProxyJump windows_machine
        User myname

ProxyJump supports full SSH syntax, so if you are jim on windows_server and it uses port 2222 for ssh. remote_server is at IP 192.168.0.110 from the windows_server then you can write:

Host remote_server
        HostName 192.168.0.110
        ProxyJump [email protected]_machine:2222
        User myname

And still just run ssh remote_server to get there.


If you are running an older version of SSH, use ProxyCommand - this allows you to tell SSH to first run a command to establish a proxy connection, before running the actual SSH command.

ssh -o ProxyCommand='ssh -W %h:%p windows_machine' remote_server

This uses the SSH -W option, which is shorthand for the more arcane netcat syntax.

Note that, as when you run ssh remote_server you are now on the windows_machine you need to ensure that you use the IP of the remove_server from the jump box rather than the IP from your machine - these may well be the same.

You can then add this directive to your ~/.ssh/config file:

Host remote_server
  HostName remote_server
  User myname
  ProxyCommand ssh -W %h:%p windows_machine

This means that if remote_server is a different machine as seen from windows_machine then you can put that in the config and still just use ssh remote_server.