Killercode
Killercode

Reputation: 904

SSH Shell Script multiple commands output

Grettings,

I want to execute 2 commands on ssh within a shell script and retrieve the output to my local machine

example

ssh user@host "command1" > /local/1.txt

ssh user@host "command2" > /local/2.txt

I want this but with a single connection is it possible

please don't answer with "Expect" solutions...

Thanks a lot ;)

Upvotes: 3

Views: 4940

Answers (3)

jfg956
jfg956

Reputation: 16730

As the previous solution with sed is broken because of end of line handling, this solution uses awk.

So to do the same as:

ssh user@host "command1" > /local/1.txt
ssh user@host "command2" > /local/2.txt

in a single connection, and without temporary file, you could do:

ssh user@host "command1 | sed -e 's/^/1/'; echo -e '\na'; command2 | sed -e 's/^/2/'; echo" | \
awk -v f1=/local/1.txt -v f2=/local/2.txt \
'BEGIN{state=0; printf "" > f1}
/^1/ {printf "%s%s", state == 1 ? "\n" : "", substr($0, 2) > f1; state=1}
/^$/ && state == 1 {printf "\n" > f1}
/^a$/ {state=2; close (f1); printf "" > f2}
/^2/ {printf "%s%s", state == 3 ? "\n" : "", substr($0, 2) > f2; state=3}
/^$/ && state == 3 {printf "\n" > f2}
END{close (f2)}'

Upvotes: 0

jfg956
jfg956

Reputation: 16730

Edit: not working if the output of command1 does not end with a new line.

Edit: also not working if one or both commands do not produce output. Needing a more flexible tool --> awk. See other solution.

To do the same as:

ssh user@host "command1" > /local/1.txt
ssh user@host "command2" > /local/2.txt

in a single connection, and without temporary file, you could do:

ssh user@host "command1 | sed -e 's/^/1/' ; command2 | sed -e 's/^/2/'" | \
sed -n -e '/^1/{s/^.//;w /local/1.txt
};/^2/{s/^.//;w /local/2.txt
}'

You need the new lines after /local/1.txt and /local/2.txt, because if they are not there, sed will keep thinking you are writing a filename.

Upvotes: 1

hmontoliu
hmontoliu

Reputation: 4019

If you don't mind to use the same file for storing the output; then:

ssh user@host "command1; command2" > /local/1-2.txt

If it matters, then try something like this:

ssh user@host "command1 > /somepath/1.txt; command2 > /somepath/2.txt; ..."
scp user@host:/somepath/*.txt somelocalpath/

If you still want just a single connection, maybe this might work for you:

ssh user@host "command1; echo "this_is_a_separator"; command2" > /local/1-2.txt
sed -n '1,/this_is_a_separator/ {p}' /local/1-2.txt > /local/1.txt
sed -n '/this_is_a_separator/,$ {p}' /local/1-2.txt > /local/2.txt

The local file splitting can be done in several other ways, that was just one of them.

Upvotes: 3

Related Questions