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.

link|improve this question

79% accept rate
feedback

4 Answers

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 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.

link|improve this answer
feedback

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 gateway.example.com &
PID=$!
nohup "sleep 600; kill $PID" &

link|improve this answer
feedback

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 :)

link|improve this answer
feedback

Look at this:

ssh -f -L 14880:internalserver:3306 gateway.example.com 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).

link|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
feedback

Your Answer

 
or
required, but never shown

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