SSH provides a feature called port forwarding, which allows you to create secure tunnels for forwarding network connections from your local machine to a remote server and vice versa. There are two types of port forwarding: local port forwarding and remote port forwarding.
Local port Forwarding:
Local port forwarding allows you to forward a port from your local machine to the remote server. This is useful when you want to access a service on the server that is not directly accessible from your local machine.
ssh -L 8080:localhost:80 user@remote-server
This command forwards local port 8080 to the remote server's port 80. You can then access the service running on the remote server by navigating to http://localhost:8080 in your local web browser. Useful when you want to access a remote service from your local machine.
Remote port forwarding:
Remote port forwarding allows you to forward a port from the remote server to your local machine. This is useful when you want to expose a local service to the outside world through the remote server.
ssh -R 2222:localhost:22 user@remote-server
This command forwards the remote server's port 2222 to your local machine's SSH port (22). Now, you can SSH into the remote server from another machine by using ssh -p 2222 user@remote-server. Useful when you want to share a local service with someone on a remote server.
Notes:
- Make sure that the SSH server on the remote machine allows port forwarding in its configuration (sshd_config). The AllowTcpForwarding option should be set to yes.
- When using port forwarding, be cautious about security. Only forward ports that are necessary, and ensure that services are secured with proper authentication and authorization mechanisms.
- Port forwarding can be a powerful tool, but misuse can lead to security vulnerabilities. Always follow security best practices.