running multiple commands through ssh and storing the outputs in different files

13,803

Solution 1

Unless you can parse the actual outputs of the two commands and distinguish which is which, you can't. You will need two separate ssh sessions:

ssh -i my_key user@ip command1 > command1.txt
ssh -i my_key user@ip command2 > command2.txt

You could also redirect the outputs to files on the remote machine and then copy them to your local machine:

ssh -i my_key user@ip 'command1 > command1.txt; command2 > command2.txt'
scp -i my_key user@ip:'command*.txt' .

Solution 2

NO, you will have to do it separately in separate command (multiple login) as already mentioned by @lanzz. To save the output in local, do like

ssh -i my_key user@ip "command1" > .\file_on_local_host.txt

In case, you want to run multiple command in a single login, then jot all your command in a script and then run that script through SSH, instead running multiple command.

Solution 3

It's possible, but probably more trouble than it's worth. If you can generate a unique string that is guaranteed not to be in the output of command1, you can do:

$ ssh remote 'cmd1; echo unique string; cmd2' |
  awk '/^unique string$/ { output="cmd2"; next } { print > output }' output=cmd1

This simply starts printing to the file cmd1, and then changes output to the file cmd2 when it sees the unique string. You'll probably want to handle stderr as well. That's left as an exercise for the reader.

Solution 4

You can do this. Assuming you can set up authentication from the remote machine back to the local machine, you can use ssh to pipe the output of the commands back. The trick is getting the backslashes right.

ssh remotehost command1 \| ssh localhost cat \\\> command1.txt \; command2 \| ssh localhost cat \\\> command2.txt 

Or if you aren't so into backslashes...

ssh remotehost 'command1 | ssh localhost cat \> command1.txt ; command2 | ssh localhost cat \> command2.txt' 

Solution 5

option 1. Tell your boss he's being silly. Unless, of course, he isn't and there is critical reason of needing it all in one session. For some reason such a case escapes my imagination.

option 2. why not tar?

ssh -i my_key user@ip 'command1 > out1; command2 > out2; tar cf - out*' | tar xf -
Share:
13,803
user1356163
Author by

user1356163

Updated on June 04, 2022

Comments

  • user1356163
    user1356163 almost 2 years

    i've set up my public and private keys and have automated ssh login. I want to execute two commands say command1 and command2 in one login session and store them in files command1.txt and command2.txt on the local machine.

    i'm using this code

    ssh -i my_key user@ip 'command1 command2' and the two commands get executed in one login but i have no clue as to how to store them in 2 different files.

    I want to do so because i dont want to repeatedly ssh into my remote host.