Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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.

share|improve this question

4 Answers 4

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.

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

share|improve this answer

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

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

 
discard

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.