I have some script to be executed on remote server(server-2) through ssh from server-1 and I have to write that output into a log file named file.log on server-1.

I am trying this: sc.sh

echo 'testing'
cp $HOME/dir1/file1 $HOME/dir2

Now, executing the sc.sh through ssh:

sshpass -p 'psswd' ssh username@server-2 "bash -s" < sc.sh | tee -a file.log
if [ $? -eq 0]; then
  echo "successfully executed the script file"
  .
  .
  .
else
  echo "failed copying due to incorrect path"
fi

Now because of tee -a file.log command, it will always return 0 even though my commands in script file fails. How can I write into log file and should check the if condition after ssh command which should work based on the ssh commands exit code?

  • In case you are using bash, see man bash -> PIPESTATUS. Also see pipefail. – rudimeier May 15 '17 at 6:48
  • @rudimeier Thanks alot – Ejjagiri Venkatesh May 15 '17 at 7:18
  • @Gilles Thanks for the edit... – Ejjagiri Venkatesh May 16 '17 at 5:11
up vote 5 down vote accepted

checking ${PIPESTATUS[0]} worked for me...

if [ ${PIPESTATUS[0]} -eq 0 ]; then
  echo "successfull"
fi

echo ${PIPESTATUS[*]} prints the exit codes of all the pipeline commands.

The answer to : "how to log the output of ssh shell?" is

  • use a simple redirect >

e.g.

ssh user@remote_host "command" > local_log_file.txt

or

sshpass -p 'psswd' ssh username@server-2 "echo 'testing'; cp dir1/file1 dir2;" > local_machine_ssh_log.txt

If you want to check the result of the cp cmmand on the remote server, I'd suggest running the if statement on the remote host as part of the command you send, immediately after running the cp command

something like:

sshpass -p 'psswd' ssh username@server-2 "echo 'testing'; cp dir1/file1 dir2;if [ $? -eq 0 ]; then   echo "successfully copied"; else   echo "failed copying due to incorrect path"; fi" > local_machine_ssh_log.txt
  • But i have few commands to run on this server-1 immediately after cp command. – Ejjagiri Venkatesh May 15 '17 at 6:19
  • @EjjagiriVenkatesh - what exactly would you like to do, and check using the if statement? – Yaron May 15 '17 at 6:24
  • in the place of commands i have to send a script file sometimes to execute, in that case how can we check. I have to check if all the commands in the sent script file are executed successfully or not? How can i check and log the output? – Ejjagiri Venkatesh May 15 '17 at 6:26
  • @EjjagiriVenkatesh - can you check the local_output.txt file in your local machine? – Yaron May 15 '17 at 6:28
  • edited my question, can you please give me solution for this? – Ejjagiri Venkatesh May 15 '17 at 6:32

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.