Reputation: 13
I am new to programming. Please be kind. :) I am trying to invoke a python script on a remote machine from a shell script on my local machine.
I knew that we can exit the python script with values ranging from 0 to 127. I am trying to exit the python script with a value of 3. I verified with a print and I see the exit value is proper on the remote machine. But on my local machine, I always see the exit value of remote script as 0.
This is my shell script on the local machine.
sshpass -p password ssh -o StrictHostKeyChecking=no [email protected] << EOF
cd /root/drm/myDir
./bla.py
echo $?
This is my python script on a remote machine:
import os
import sys
for curr_tc in range(1,10):
cmd = '..........'
os.system(cmd)
:
:
:
:
if 'PASSED' in lineList[-5]:
continue
else:
exit(curr_tc)
exit(0)
Please point my mistake. Thanks in advance.
Upvotes: 0
Views: 157
Reputation: 1479
You could rewrite without using EOF like so:
result=$(sshpass -p password ssh -o StrictHostKeyChecking=no [email protected] 'cd /root/drm/myDir;./bla.py;echo $?')
echo $result
This will run all the commands on the host including expansion of the $?. When using the EOF thing, the expansion happens on your local machine as that other guy
noted. Tested on my machines with a simple bash script that just ran exit 3
and it worked.
You could then compare the result using a simple if statement like this:
if [ $result -eq 3 ]; then
echo "The process completed successfully."
else
echo "Process returned unexpected return code $result."
# Do whatever you need to if this happens.
fi
Upvotes: 0
Reputation: 123650
The reason why this fails is that $?
is expanded on the client side.
The best way to fix this is to not inspect the value on the server side at all, and instead let it get propagated to the client side:
sshpass -p password ssh -o StrictHostKeyChecking=no [email protected] << EOF
cd /root/drm/myDir
./bla.py
EOF
echo "SSH relayed the exit code, look: $?"
This allows it to work with all forms of if
statements, set -e
, or other ways of inspecting exit codes on the client.
The alternative way is to make sure the $?
is escaped by quoting the here document:
sshpass -p password ssh -o StrictHostKeyChecking=no [email protected] << "EOF"
cd /root/drm/myDir
./bla.py
echo "The command exited with $?"
EOF
echo "SSH relayed the exit code of echo itself, check it out: $?"
This will print the exit code correctly, but ssh
itself will always count it as a success because the last command, echo
, successfully printed stuff.
Upvotes: 2