To start local forwarding, use the below command which will forward connections from local port 9001 to localhost:3306 on example.com server.
ssh -N -L 9001:localhost:3306 [email protected]
To connect with the destination, use localhost:9001 on local machine.
Useful flags are:
-N - Do not execute a remote command. This is useful for just forwarding ports
-g - Allows remote hosts to connect to local forwarded ports.
To start remote forwarding, execute the following command
ssh -N -R 9000:localhost:4200 [email protected]
The remote server example.com opens port 9000 and forwards all connections to localhost:4200 on local machine.
Note 1: By default, OpenSSH only allows connecting to remote forwarded ports from the example.com host, the GatewayPorts parameter of sshd_config allows to change this.
GatewayPorts no - prevents connecting to forwarded ports from outside of example.com server
GatewayPorts yes - allows anyone to connect to the forwarded ports.
GatewayPorts clientspecified - client can specify an IP address from which connections to the port are allowed
If clientspecified
is set, the syntax of remote forwarding command will be following (only 1.2.3.4 ip address is allowed to connect with example.com's port 80 and then its connection is forwarded to port 8080 of localhost):
ssh -N -R 1.2.3.4:80:localhost:8080 [email protected]
Note 2: The forwarded remote port can be specified as 0, and the server will dynamically allocate a port and print it to standard output.