Rajesh Rajesh - 1 year ago 95
Bash Question

How to do file transfer inside ssh command line?

I have to transfer a file from server A to B and then needs to trigger a script at Server B. Server B is a Load balance server which will redirect you either Server B1 or B2 that we dont know.

I have achieved this as below.

sftp user@Server
put file

then executing the below code to trigger the target script

ssh user@Server "script.sh"

But the problem here is as I said it is a load balance server, Sometimes I am putting file in one server and the script get triggers in another server. How to overcome this problem?

I am thinking some solutions like below

ssh user@server "Command for sftp; sh script.sh"

(i.e) in the same server call if I put and triggers it will not give me the above mentioned problem. How can I do sftp inside ssh connection? Otherwise any other suggestions?

Answer Source

if you're just copying a file up and then executing a script, and it can't happen as two separate commands you can do:

gzip -c srcfile | ssh user@remote 'gunzip -c >destfile; script.sh'

This gzips srcfile, sends it through ssh to the remote end, gunzips it on that side, then executes script.sh.

If you want more than one file, you can use tar rather than gzip:

tar czf - <srcfiles> | ssh user@remote 'tar xzf -; script.sh'

if you want to get the results back from the remote end and they're files, you can just replicate the tar after the script…

tar czf - <srcfiles> | ssh user@remote 'tar xzf -; script.sh; tar czf - <remotedatafiles>' | tar xzf -

i.e. create a new pipe from ssh back to the local environment. This only works if script.sh doesn't generate any output. If it generates output, you have to redirect it, for example to /dev/null in order to prevent it messing up the tar:

tar czf - <srcfiles> | ssh user@remote 'tar xzf -; script.sh >/dev/null; tar czf - <remotedatafiles>' | tar xzf -
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download