If ssh is trying to read from stdin for some reason -- it shouldn't, but your implementation may be different than mine -- it may 'eat' the lines being redirected into the loop. Try this: while read...
In fact you do quite the same in a script. The following is a sketch which can perhaps be refined once we know a bit more about your environment, but it is a place to start. Save the following to a...