I often rely on SSH tunnels to forward remote ports locally. For example, to control my remote installation of Resilio Sync. There is a lot of flags you can set, but these are the flags that work best for me:
ssh -CqTnNf -L 8889:localhost:8888 [email protected]
In this example, I forward the remote localhost:8888 port to my local 8889. The flags do the following:
C: Compress the data.q: Silent modus.T: Disable pseudo-tty allocation.n: Prevent reading stdin.N: No remote commands, just forwarding.f: Run in the background.L: Specifies the forward.
Now, if you want to exit the tunnel, you could kill SSH pkill ssh, but this will kill all your SSH connections. I multiplex my connections and can run: ssh -O exit [email protected]. You would need this in your ~/ssh/.config to be able to do that as well:
Host *
ControlMaster auto
ControlPath ~/.ssh/sockets/%r@%h-%p