Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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

share|improve this question
up vote 2 down vote accepted

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

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

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

share|improve this answer

The expect package has the timeout command as one of its examples. You could wrap your whole script with a call to that.

Or something like:

ssh -f -N -L 14880:internalserver:3306 &
nohup "sleep 600; kill $PID" &

share|improve this answer

Look at this:

ssh -f -L 14880:internalserver:3306 sleep 3m

This will setup a tunnel and will let you connect in 3minutes. If you connect it will be available until it becames idle. This will not kill a running backup process however (I hope this is what you want).

share|improve this answer
Close, but I'm not worried about nothing connecting in 3 minutes. I'd much rather have a way to kill the tunnel after X time. – Rory Jul 23 '09 at 14:13
@cstamas: this might not have been what Rory was looking for, but was exactly the gem that I needed. Thanks! :] – Tomislav Nakic-Alfirevic Dec 19 '12 at 15:53
@TomislavNakic-Alfirevic you are welcome ;-) – cstamas Dec 20 '12 at 10:29

Another way of doing this would be setting the idle-timeout value on your session. This can be done on the server in the sshd_config with the "IdleTimeout" value, or by the user in the authorized_keys file as an "idle-timeout=6m ...key...". Or hours. Or seconds. Section 8.2.7 in oreilly's "SSSH The Secure Shell" book. After said amount of inactivity (no input), your processes will be killed. How clean that is depends on how well they respond to hups :)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.