How do I stop my ssh tunnel when it is in the background?

I'm using this ssh command:

ssh -fnN -L $LOCALPORT:$REMOTEHOST:$REMOTEPORT $HOST

This creates my ssh connection in the background and forwards that port to the remote host through another host. This is great, and allows me to use my service behind a firewall by connecting to a server which can access both networks.

I need to stop this ssh connection when done, and I'm not sure how.


Find the PID with the ps command and send it a QUIT signal with the kill command.

Find the PID with:

ps -o pid,cmd | grep ssh

Send the QUIT signal with:

kill -QUIT <pid>

The best solution I found is following to kill all the tunnels:

ps -o pid,cmd|grep "ssh -L"|grep -v grep|awk '{print $1}'|xargs kill

  1. Gets id and command of all processes
  2. Filter for ssh -L
  3. gets the process id and kills it