Chaining SSH Tunnels

[Update 18/3/2009: added single-tunnel example]

This post is mainly for my own benefit, because every time I need to do this I find I’ve forgotten how and need to look it up again.

Say you want to reach dest, but have to tunnel through foo because you don’t have direct access to port 22 on dest.

ssh -NL 65001:dest:22 foo &
ssh localhost -p 65001
Welcome to dest!

If you need to tunnel through multiple gateways to reach the machine you want to connect to, this is how to do it. Now let’s say you have to jump through foo, bar and wibble to get to dest.

ssh -NL 65001:bar:22 foo &
ssh -NL 65002:wibble:22 localhost -p 65001 &
ssh -NL 65003:dest:22 localhost -p 65002 &
ssh localhost -p 65003
Welcome to dest!

Obviously you don’t need to use ports starting with 65001, but can pick any convenient unused local ports.

You can use different usernames and SSH ports if necessary, eg if you have to connect to wibble as dave on port 222, that line becomes:

ssh -NL 65002:[email protected]:222 localhost -p 65001

Technorati Tags: , ,