How do I establish a bidirectional SSH Tunnel

Barry picture Barry · Apr 13, 2013 · Viewed 16.1k times · Source

Is it possible to do the following via an SSH tunnel...

  1. Host-1 establishes an SSH connection to a Remote Server
  2. I wish to log into the Remote Server and execute commands over SSH back on Host-1

Host-1 is a device that I will not have access to directly. Host-1 is set up to automatically establish an SSH connection to a remote server via cron. At any point while Host-1 has established an SSH connection to the Remote Server, I wish to log into the Remote Server in order to perform maintenance on Host-1 via SSH.

I am looking for an example of how this would work if its possible.

Answer

BraveNewCurrency picture BraveNewCurrency · Apr 13, 2013

Like this:

host1$  ssh -N -R 8822:localhost:22 remote.host.com

The optional -N says "don't execute a command" (helpful to prevent accidents caused by leaving remote shells laying around.)

Now from remote, you can SSH to host1 like this: (The remote port 8822 forwards to host1, but only on the loopback interface.)

remote$ ssh -p 8822 localhost

For extra credit, you can export the forwarding to the whole world, allowing anyone get to host1 by hitting remote's port 8822. (Note the extra initial colon)

host1$  ssh -N -R :8822:localhost:22 remote.host.com