Kill connection and try again

I have a pretty hefty script that does some SSHing to different boxes. It's a pain in the butt if it gets so far and fails to connect to the last box. Is there a way of timing out on an ssh if it fails to connect and retrying?

pseudo code:

ssh $user@$server "dosomething; dosomethingelse"
if [ 20 seconds passed and not connected]
drop connection
retry ssh
fi

My last script got stuck and I was pretty disappointed. Maybe some kind of loop would help.

Thanks in advance

This isn't a complete answer but you can make ssh timeout by using:

ssh -o ConnectTimeout=5 <user>@<host>...

In this case the timeout would be 5 seconds but you can set that to whatever. What I don't know is what the result of the ssh is if it times out. Maybe if you have a box you know will timeout you can check it. Echo the exit code after it runs:

echo $?

If it times out and the exit code is anything other than 0 you can trigger off that and retry. If it times out and the exit code is 1 this may not work because if the ssh fails for other reasons you might get into a loop. Maybe you could set it up to retry a certain number of times and then fail.

Anyway, hope this helps.

I'd suggest using the 'Search' of the forums looking for 'TIMEOUT' - there're multiple threads dealing with that.
Such as this and this and others........