How to get to a service/server which is on an inaccessible network (using SSH tunnels)

shell prompt image

In the latest of our ‘just the examples’, imagine you are in a scenario where you want to ssh to a server (or even browse a web page etc) on a server you cannot directly get to. You do, however have access from your box (localhost) to a server (server1) that can connect to that server (let’s call that server2).

Here’s how to ssh tunnel that shit!

Let’s assume that your username is bob, but the only account you have access to on the far host (server2) is called tom, just for clarity sake.

Tunnel from localhost to server1 and from localhost to server2:

ssh -L 9998:tom@server2:22 -N bob@server1
ssh -p 9998 tom@localhost

You’ll notice when you log into server 1 on the first line, it just sits and hangs there. That’s because it’s established the tunnel. Simply hit ctrl+z and type ‘bg‘ to background the ssh process before heading on to ssh through the tunnel.

If you want it super secure, you need an extra hoop: This example will open a tunnel from localhost to server1 through which the SSH service on server2 can be used. Then a second tunnel is opened from localhost to host2 through the first tunnel.

ssh -L 9998:tom@server2:22 -N bob@server1
ssh -L 9999:tom@localhost:1234 -N -p 9998 localhost

Here’s a great link with some more examples and explanations:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.