I think you're just trying to copy files from the server behind NAT via gatewayserver.
I'd suggest you more simple solution.
Set up password-less authentication (put private key from your desktop/Mac to both mentioned servers)
Use smthsomething like
ssh -MNf -L 60022:storageserver:22 username@gatewayserver
to set up ssh tunnel via gatewayserver. Now your Mac's port 60002 has direct connection to port 22 of storageserver. 3. At this point you may copy files directly via this tunnel:
scp -P 60022 -R username@localhost:/path/to/folder . Put these commands into your bash script and you will achieve what you want.
UPD:
Putting it all together, here's complete script:
#!/bin/bash # set up tunnel ssh -MNf -L 60022:storageserver:22 gatewayserver_username@gatewayserver || true # copy files __directly__ into correct backup folder scp -P 60022 -R "storageserver_username@localhost:/remote/path/to/retrievedfolder/at/storageserver" "/local/path/to/backup/retrievedfolder.`date +%Y%m%d`" Prerequisites (run just one time on your Mac):
# Create SSH keys @ local machine ssh-keygen # Put your local SSH key to the gateway server ssh-copy-id gatewayserver_username@gatewayserver # Enable tunnel (will not ask your password if previous steps are correct) ssh -MNf -L 60022:storageserver:22 gatewayserver_username@gatewayserver # Put your local SSH key to the storageserver server ssh-copy-id -p 60022 storageserver_username@localhost