Skip to content

Instantly share code, notes, and snippets.

@michalstala
Created September 30, 2018 21:39
Show Gist options
  • Save michalstala/df692855d80219c1b02ca8179bc5b9c2 to your computer and use it in GitHub Desktop.
Save michalstala/df692855d80219c1b02ca8179bc5b9c2 to your computer and use it in GitHub Desktop.
Local and Remote SSH port forwarding

Local SSH Port Forwarding

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 username@example.com

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.

Remote SSH Port Forwarding

To start remote forwarding, execute the following command

ssh -N -R 9000:localhost:4200 username@example.com

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 username@example.com

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.

Reference

https://www.ssh.com/ssh/tunneling/example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment