My understanding is that when you run the ssh commands manually they work, but the script that does essentially the same seems to be failing?
If so, could you print out the ssh commands from the script and run those manually to check if that works? Could you also share the ssh commands printed out by the script? It could possibly be a bug in the script.