For example, you're on local.example.com
and want to connect to remote.example.com
on port 25 (SMTP), but a firewall is stopping you.
- ssh access to
remote.example.com
, or to another machine that can accessremote.example.com
on port 25.
We get our ssh client to listen on a port on local.example.com
(we'll use 1025). This will forward traffic through to remote.example.com
on port 25.
ssh remote_user@remote.example.com -L 1025:localhost:25
-L
open a port on the local machine,local.example.com
1025
the port number to open (the local end of the tunnel)localhost
the remote host to which to forward traffic. This is resolved onremote.example.com
, hencelocalhost
25
the port to which to forward traffic (the remote end of the tunnel)
Now, when you connect to port 1025 on local.example.com
, traffic is forwarded to port 25 on remote.example.com
. For example, you could point your e-mail client at localhost:1025
.
Maybe you can't connect directly to remote.example.com
. It may not even have an ssh server running. However, you know that gateway.example.com
can. In this case, ssh into the gateway and tell it to connect onwards to remote.example.com
:
ssh user@gateway.example.com -L 1025:remote.example.com:25
The name of the remote host is resolved by the gateway. As long as the gateway can resolve remote.example.com
it will work. It doesn't even matter if the local machine knows nothing about remote.example.com
.
In a similar way, ssh can open a port on the remote machine. You might need this if a firewall at work won't let you ssh in from home (but does let you ssh out to your home machine).
In this example, we'll use work.example.com
and home.example.com
.
At work, do:
ssh home_user@home.example.com -R 1022:localhost:22
-R
open a port on the remote machine,home.example.com
1022
the port number to open (the remote end of the tunnel)localhost
the remote host to which to forward traffic. This is resolved onhome.example.com
, hencelocalhost
22
the port to which to forward traffic (the local end of the tunnel)
Now at home, where you can't ssh directly to work.example.com
, you'll have a new port (1022) open, to which you can connect.
Because 1022 is not the standard ssh port, you need to use the -p
option. Don't forget to use your work username here:
ssh -p 1022 work_user@localhost
You can supply more than one -L
or -R
option:
ssh remote_user@remote.example.com -L 1025:localhost:25 -R 1080:home.example.com:80