4

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.

4 Answers 4

2

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.

2

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" &

2

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

3
  • 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. Jul 23, 2009 at 14:13
  • @cstamas: this might not have been what Rory was looking for, but was exactly the gem that I needed. Thanks! :] Dec 19, 2012 at 15:53
  • @TomislavNakic-Alfirevic you are welcome ;-)
    – cstamas
    Dec 20, 2012 at 10:29
1

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .