How to set up SSH port forwarding

SSH port forwarding is a nice feature that allows to create encrypted tunnels over unsecured network. It is easy and straightforward to remember and use in daily work so I will describe it here with couple of examples.

Port Forwarding

To forward port 443 from to localhost port 9443 using ssh server (and user milosz) execute command:

$ ssh [email protected] -L 9443:

To forward multiple ports just define more -L parameters:

$ ssh -L 9443: -L 9080:

To specify non standard port for ssh server add -p parameter:

$ ssh -p 4000 -L 9443:

To force ssh to stay in foreground but not execute any command use -N parameter:

$ ssh -N -L 9443:

To force ssh to go to background use -N -f parameters:

$ ssh -N -f -L 9443:

To listen on all interfaces and allow remote hosts to connect locally forwarded ports use -g parameter:

$ ssh -g -L 9443:

Command above is equal to:

$ ssh -g -L *:9443:

You can specify local IP address to listen on ( in this example):

$ ssh -g -L

Reverse port forwarding

To access local port 80 on remote ssh server use -R parameter:

$ ssh -R 36001:localhost:80

Use -N -f parameters as in the examples above. As this connection is usually slower you can enable compression by using -C parameter.


To create SOCKS proxy on port 9999 use -D parameter:

$ ssh -D 9999

Debug information

In case of any problems you can easily read debug information using -v parameter:

$ ssh  -Nv [email protected] -p 4000 -D localhost:9999
OpenSSH_5.9p1 Debian-5ubuntu1, OpenSSL 1.0.1 14 Mar 2012
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to [] port 4000.
debug1: Connection established.
debug1: Next authentication method: password
[email protected]'s password: *************
debug1: Authentication succeeded (password).
Authenticated to ([]:4000).
debug1: Local connections to LOCALHOST:9999 forwarded to remote address socks:0
debug1: Local forwarding listening on ::1 port 9999.
debug1: channel 0: new [port listener]
debug1: Local forwarding listening on port 9999.
debug1: channel 22: free: direct-tcpip: listening port 9999 for port 80, connect from port 56969, nchannels 20
debug1: channel 23: free: direct-tcpip: listening port 9999 for port 80, connect from port 56970, nchannels 19

To check open ports use netstat command:

$ sudo netstat -tapn | grep ssh
tcp        0      0*               LISTEN      17391/ssh       
tcp        0      0            ESTABLISHED 17391/ssh       
tcp6       0      0 ::1:9999                :::*                    LISTEN      17391/ssh 

To change port forwardings during the SSH connection read this post.

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system. He is also open for new opportunities and challenges.