How to Append the output of a script running in remote server to a file in local server?

Hi guys,

So i am in server1 and i have to login to server 2, 3,4 and run some script there(logging script) and output its result. What i am doing is running the script in server2 and outputting it to a file in server 2 and then Scp'ing the file to server1. Similarly i am doing this for other servers.

After getting all the 3 files in my local server, i am appending all 3 into a master file.

Is there a way to directly output result of script in remote server to a file in my local server and keep appending for other remote servers?

Content of Script1:

 
 
zcat /logs/jvm1/Audit.log.gz | grep 'Exception' >/tmp/AuditlogServer1.txt
scp /tmp/AuditlogServer1.txt userid@server1:/tmp/
fi
 
 
ssh -x server2 "/bin/sh -s" < Script1.sh

Remove the redirection from Script1, and try putting all server logins into one script, e.g. Scr2:

ssh -x server2 "/bin/sh -s" < Script1.sh
ssh -x server3 "/bin/sh -s" < Script1.sh
ssh -x server4 "/bin/sh -s" < Script1.sh

and run this like

./Scr2 >/tmp/TotalLog.txt

or, put an exec >/tmp/TotalLog.txt into the first line of Scr2

1 Like

You can simply collect stdout from the script.
First change Script1.sh to produce stdout:

zcat /logs/jvm1/Audit.log.gz | grep 'Exception'

Then run it from server1 as

for server in server2 server3 server4
do
 ssh -x $server "/bin/sh -s" < Script1.sh > /tmp/Auditlog_${server}.txt
done

or all-in-one

for server in server2 server3 server4
 ssh -x $server "/bin/sh -s" < Script1.sh
done > /tmp/Auditlog_all.txt
1 Like

This worked perfect. Thanks. I have another query.

Suppose one of the servers does not have the file Audit.log.gz present , the script skips that server with an error message "Audit.log.gz not found" . How Can i log that error message and the corresponding server in another text file ?

Redirect stderr to another text file to capture the err msg. If you need the server as well, you have to take care of that in your script, e.g. echo the server name to stderr if an exit code is not zero.

stderr is redirected with 2> .
For example

for server in server2 server3 server4
 ssh -x $server "/bin/sh -s" < Script1.sh 2> /tmp/ErrorLog_${server}.txt
done > /tmp/Auditlog_all.txt