Ssh – Kill an SSH tunnel after X minutes even if it’s still being used

networkingprocesssshssh-tunneltunneling

I'm setting up some background SSH tunnel for some backup procedures. However I'm worried the ssh process just sitting around. At the end of my script I kill the PID, but what if something happens to my script and it doesn't finish. I want something that's a bit more robust.

Is there anyway to get the SSH tunnel to kill itself after X seconds / minutes?

At the moment I'm starting it like this

ssh -f -N -L 14880:internalserver:3306 gateway.example.com

And then using lsof to get the PID that's opened that port.

Best Answer

Here's a cleaner way of doing it that has been proposed before:

ssh -f -N -L 14880:internalserver:3306 gateway.example.com &
PIDSSH=$!
( sleep 600 ; echo "Timeout." ; kill $PIDSSH ) &
PIDSLEEP=$!
wait $PIDSSH
kill $PIDSLEEP && echo "Session ended before timeout"
wait

However you don't get an error code from ssh, but that could be arranged.