I have a Shell script that handles Satellite server and Redhat IDM registrations. I don't have rights to update the script. The -i argument in the command below is for IDM registration and -s for Satellite server registration.
/usr/local/sbin/new-clone.sh -i aws -s aws-prod
Error handling is done as follows: Satellite registration:
if [ "${RETURN_VALUE}" -ne 0 ]; then
echo -e "\n\nSatellite registration failed. Please correct and re-run this script.\n\n"
exit 2
fi
IDM registration:
idm_failed ()
{
echo -e "\n- IDM registration failed to 1ドル. This script did not complete. Please check network connection between this system and 1ドル servers. Re-run this script after troubleshooting. Exiting.."
exit 2
}
I am executing the Shell script from Python as follows.
The server.execute_script command is proprietary to a COTS application.
registration_command = "/usr/local/sbin/new-clone.sh -i aws -s aws-pro"
join_script = """#!/bin/bash
{}
yum clean all
yum -y upgrade
systemctl reboot && exit 0
""".format(registration_command)
try:
server.execute_script(script_contents=join_script, runas_username='ec2-user', run_with_sudo=True,timeout=1200)
except:
logger.info('Failed with SEC satellite or IDM')
I want to update the logic in this try-catch statement so that it's more specific to whether the issue was with IDM registration or the Satellite registration. Since both these functions have a return code of 2, I was wondering it's possible to use the output of the echo command to implement. I would love to hear from the community on what makes sense here.
Please stay safe and be kind.
-
Does this answer your question? Calling an external command from PythonJongware– Jongware2020年04月02日 14:51:08 +00:00Commented Apr 2, 2020 at 14:51
2 Answers 2
I think that the subprocess module would be perfect for you. If you run:
import subprocess
res = subprocess.run('your command',shell=True, capture_output=True, check=True)
# try to run it with 'ls -l' and check the returned response.
You will be able to get the returncode, stdout, stderr using: res.returncode, res.stdout, res.stderr and if the command fails, it will throw exception.
3 Comments
server.execute_script to execute the command. This command handles authentication to the remote server. server.execute_script returns the output from the from the script's execution. So, is it possible to parse it in Python?You could change one of the exit codes and have it printed with:
try:
server.execute_script(script_contents=join_script, runas_username='ec2-user', run_with_sudo=True,timeout=1200)
except Exception as e:
logger.info('Failed with error:\n{}'.format(e))
Normally this will print the error message with the exit code.