Mastering SSH Tunneling: Options and Configurations
Ohidur Rahman Bappy
MAR 22, 2025
Mastering SSH Tunneling: Options and Configurations
Introduction
SSH tunneling is a powerful tool for securely forwarding ports and executing commands over a secure connection. This guide explores various SSH tunneling options and configurations to optimize your workflow.
SSH Login Shell Options
Basic SSH Tunneling
Consider the following command:
ssh -L 5000:localhost:3306 user@remote-server.com
This establishes a tunnel and logs you into the remote server. To perform port forwarding without a remote login session, use the -N
option:
ssh -N -L 5000:localhost:3306 user@remote-server.com
-N
: After connecting, it hangs without a shell prompt. Only works with SSHv2.
To avoid requesting a pseudo-terminal, add -T
:
ssh -T -N -L 5000:localhost:3306 user@remote-server.com
-T
: Disables pseudo-terminal allocation, safe for binary file transfers.
Automating SSH Tunneling via Cron
To establish an SSH tunnel through cron, ensuring it runs in the background, use:
ssh -f -L 5000:localhost:3306 user@remote-server.com
-f
: Sends SSH to the background before executing the command.
Combine options for full cron readiness:
ssh -f -T -N -L 5000:localhost:3306 user@remote-server.com
Note: Requires key authentication as cron cannot handle passwords.
Connecting to Non-standard Ports
For SSH servers on non-standard ports, specify the port with -p
:
ssh -T -N -L 5000:localhost:3306 user@remote-server.com -p 1022
-p
: Specifies the port on the remote host.
Using Non-standard Private Keys
When managing multiple private keys, specify the key with -i
:
ssh -T -N -L 5000:localhost:3306 user@remote-server.com -i ~/.ssh/custom_key
Streamlining with SSH Config Files
Simplifying Commands with an Alias
Edit your SSH config file:
$ vim ~/.ssh/config
Host alias
HostName remote-server.com
User user
Simplified command:
ssh -f -T -N -L 5000:localhost:3306 alias -p 1022 -i ~/.ssh/custom_key
Including Port and Key in Config
Extend your config:
$ vim ~/.ssh/config
Host alias
HostName remote-server.com
User user
Port 1022
IdentityFile ~/.ssh/custom_key
Now the command:
ssh -f -T -N -L 5000:localhost:3306 alias
Adding Tunnel-specific Config
For a dedicated tunnel setup:
$ vim ~/.ssh/config
Host tunnel-alias
HostName remote-server.com
User user
Port 1022
IdentityFile ~/.ssh/custom_key
LocalForward 5000 localhost:3306
Establish the tunnel easily:
ssh -f -T -N tunnel-alias
Conclusion
By understanding these options, you can streamline your SSH tunneling practices and ensure secure, efficient connections tailored to your needs.