How to configure a shortcut for an SSH connection through a SSH tunnel

Solution 1:

As a more concrete version of Kyle's answer, what you want to put in your ~/.ssh/config file is:

host foo
  User webby
  ProxyCommand ssh a nc -w 3 %h %p

host a
  User johndoe

Then, when you run "ssh foo", SSH will attempt to SSH to johndoe@a, run netcat (nc), then perform an SSH to webby@foo through this tunnel. Magic!

Of course, in order to do this, netcat needs to be installed on the gateway server; this package is available for every major distribution and OS.

Solution 2:

You can use the ProxyCommand directive in your ~/.ssh/config file, for example to use netcat as the relay:

host server2
    ProxyCommand ssh server1 nc server2 22

The you would just use 'ssh server2'. The man page information for this directive is found in 'man ssh_config'


Solution 3:

I prefer a different approach that maintains a pre-authenticated tunnel to the gateway server. In ~/.ssh/config:

Host a
    ControlMaster auto
    ControlPath ~/.ssh/control-master/%r@%h:%p

Then in .bashrc:

s () {
        if ( ssh -O check a 2>&1 > /dev/null 2>&1 )
        then
                ssh -t a ssh $1
        else
                if [[ -S ~/.ssh/control-master/insyte@a:22 ]]
                then
                        echo "Deleting stale socket..."
                        rm ~/.ssh/control-master/insyte@a:22
                fi
                echo "Opening master session..."
                if ssh -Nf a
                then
                         ssh -t a ssh $1
                fi
        fi
 }

So to connect to foo:

s foo

The first time you connect it will authenticate you against "a" and open a persistent, backgrounded ssh tunnel. Subsequent calls to "s" will open almost instantaneously through the pre-authed tunnel.

Works great.


Solution 4:

This can be accomplished by doing ssh -At johndoe@a ssh webby@foo. The -A command forwards your ssh agent (so you can avoid having to re-authenticate on the proxy), while the -t ensures a terminal exists on the proxy. The following bash function may be useful:

ssh-bounce () {
    local cmd=""
    for i in "$@"; do
        cmd+="ssh -At $i "
    done
    $cmd
}

Solution 5:

This type of functionality exists in newer versions of OpenSSH 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