Categories
Software

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:dave@wibble:222 localhost -p 65001

[tags]ssh, chain, tunnel[/tags]

One reply on “Chaining SSH Tunnels”

ssh -t foo ssh -t bar ssh -t -p222 dave@wibble ssh -t dest

Welcome to dest is one command line and no backgrounds to clean up.

This is better if all you want is the shell session at dest. End to end port forwarding does not work and has to be explicitly chained. But that can still be done all in one command by making each ssh step connect to the next with the appropriate -L on each.

Leave a Reply