I have a flask api which triggers a bash script and get its exit code for further processing .I am using Subprocess module. But when i try to capture the return code for further processing it is always 0 even if the script failed..
for testing if i run the same piece of code using a python script it works fine
Below is my API code
@app.route("/test1", methods=['POST', 'GET'])
def testfunc1():
path = "/home/admin/temp1"
if request.method == "POST":
try:
payload = request.json
password = payload["password"]
password_bytes = bytes(password + '\n', encoding='utf-8')
dpath = "/home/admin/temp1/New-folder"
proc = subprocess.Popen(['sudo', '-S', 'sh', os.path.join(dpath,'test1.sh')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate(input=password_bytes)
if proc.returncode == 0:
logger(level="exception", message=str(proc.returncode))
response = response_handle(response="success",code=200)
return response
else:
logger(level="exception", message=str(proc.returncode))
proc = subprocess.Popen(['sudo', '-S', 'sh', os.path.join(dpath,'test1.sh')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate(input=password_bytes)
response = response_handle(response="Done",code=200)
return response
except Exception as err:
logger(level="exception", message=str(err))
response = response_handle(code=500, response=str(err))
return response
Even my shell script fails it returns returncode as '0'
Below is my shell script
#!/bin/sh
tar -xf "/home/admin/temp1/New-folder/upgrade.tar.gz" #tar file does not exist
error_code=$?
if [ $error_code -eq 0 ]; then
echo Untar is completed
else
echo ERROR: {Error Code: $error_code, Error Message: Can Not Untar}
exit $error_code
fi
below is my python code
import subprocess
import os
dpath = "/home/admin/temp1/New-Folder"
password = "password"
password_bytes = bytes(password + '\n', encoding='utf-8')
proc = subprocess.Popen(['sudo', '-S', 'sh', os.path.join(dpath,'test1.sh')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate(input=password_bytes)
print(proc.returncode)
print(out)
print (err)
if proc.returncode == 0:
print("success")
else:
print("fail")
Output for my python script
2
b'ERROR: {Error Code: 2, Error Message: Can Not Untar}\n'
b'tar: /home/admin/temp1/New-folder/upgrade.tar.gz: Cannot open: No such file or directory\ntar: Error is not recoverable: exiting now\n'
fail
Output for my api
api/api_server.py:3717 :: 0 #return type
and reponse is success
Not sure what is wrong
please help :)