The ssh command isn’t only for accessing a shell on remote systems. It can also be used to tunnel traffic or view remote web applications without having to mess around with firewalls.
As an example, the other day I installed Grafana on a Linux server in the cloud. To quickly view the web UI on my local machine I can use ssh
with the -L
option to forward a local port to the Grafana port (default: 3000) on my server
ssh -L 3000:server:3000 server
Navigating to localhost:3000 in my browser gives me access to Grafana. This is great except I have to leave a terminal open for the ssh
session. Adding the -N
option tells ssh
not to run a remote command, if you try this the connection will open but you won’t get a prompt on the server. Also adding the -f
option puts ssh
into the background, freeing up the terminal
ssh -NfL 3000:server:3000 server
In order to close the connection you will have to find the PID then kill it. Not very eloquent. My preference is to use the ControlMaster
option in my ~/.ssh/config, something that I use for sharing ssh
connections (see my ssh-aring is caring post).
By adding the ControlMaster
and ControlPath
options into ~/.ssh/config allows ssh
to manage these connections. You can use the -O
option to pass control commands (ctl_cmds
)
ssh -O check server
Master running (pid=1511266)
You can also look in the path specified by ControlPath
to see the sockets. Closing the background connection is now clean and tidy
ssh -O exit server
For port forwarding connections that I use regularly I add the options into ~/.ssh/config, making my life easier. For the example above I would add
Host server
HostName server
LocalForward 3000 server:3000
ForkAfterAuthentication yes
SessionType none
Now I can incant
ssh server
This opens the connection and puts it into the background allowing me to continue with my local terminal session and view Grafana on my remote server.