7

I have two servers

Server1 -> Static IP1 
Server2 -> Static IP2

Server2's firewall allows access only from Static IP1

I can connect to Server1 via ssh from anywhere.

How can I connect to Server2 from my PC which is behind a dynamic IP via ssh in one step instead of connecting via ssh to Server1 and then doing another ssh to Server2 from within Server1s shell.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
gabtzi
  • 173
  • 1
  • 3

2 Answers2

11

If you have OpenSSH 7.3p1 or later, you can tell it to use server1 as a jump host in a single command:

ssh -J server1 server2

See fcbsd’s answer for older versions.

Stephen Kitt
  • 434,908
  • 1
    I just tried and it gives me unknown option -- J usage: ssh [-1246AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port] [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-L address] [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] [user@]hostname [command] – gabtzi Feb 10 '18 at 12:01
  • Ah, yes, you need OpenSSH 7.3p1 or later. – Stephen Kitt Feb 10 '18 at 12:11
  • 2
    If you don't have -J you can emulate it using -W and a ProxyCommand directive. – Daniel Pryden Feb 10 '18 at 14:28
  • 2
    Also, you can add a host configuration to your ~/.ssh/config so that connections to server2 always jump through server1. This allows you to use commands like scp and rsync against server2 transparently. – Daniel Pryden Feb 10 '18 at 14:30
  • Adding a host configuration to ~/.ssh/config as per https://unix.stackexchange.com/a/25080/275310 was the one that worked for me for my setup and was easier to understand and use. Nonetheless answers here were a very interesting read and helped me understand things better. – gabtzi Feb 10 '18 at 18:27
  • I also tested with updated openssh version and seems to work OK too with the parameter -J – gabtzi Feb 10 '18 at 18:36
  • @DanielPryden Your comments would actually be the best answer for anybody using a distribution which doesn't have 7.3 yet such as Ubuntu LTS. – kasperd Feb 10 '18 at 19:15
4

You need to use ssh port forwarding and depending on what you want you either want the -L option or the -R option.

ssh server1 -g -L 2222:server2:22

the -g allows remote hosts to connect to local forwarded ports, and the -L sets up a connection on server1 port 2222 to connect to server2 port 22.

Thus on server1 ssh localhost -p 2222 will connect you to server2.

If you have problems use -vvv that will help give lots of debugging output.

The -R sets up a reverse tunnel, so connections on the remote host are forward to the local side.

fcbsd
  • 689