I use perl and perl-expect to do this sort of thing.
It can get very complex, but using expect to control the SSH session and allow error handling it will do what you want.
There was once a program out there called remote_update-1.6 by Viraj Alankar that I was very impressed with. For my uses I had to totally rewrite it to meet my needs but it will get you where you need to be.