Run shell commands from a list and check exit codes with python
Hi everyone! I’d like to share a small Python script I originally wrote for a one-time personal task. While it was created for a specific need, I believe it could be useful in everyday sysadmin work.
The code snippet:
import subprocess
import logging
logging.basicConfig(
level=logging.INFO,
format='%(levelname)s: %(message)s'
)
logger = logging.getLogger("demo-script")
def run_command(command):
logger.info(f"Trying to run command: {command}")
result = subprocess.run(
['bash', '-c', command],
capture_output=True,
text=True
)
logger.info(f"Exit code: {result.returncode}")
if result.returncode == 0:
logger.info(f"SUCCESS: {command}")
else:
logger.error(f"FAILURE: {command}")
if result.stderr:
logger.error(f"STDERR: {result.stderr.strip()}")
def main():
logger.info("Starting script")
commands = [
"df -h",
"hostname",
"ping 8.8.8.8 -c 1",
"cp /etc/no/such/file /tmp/" # Broken command for demonstration
]
for cmd in commands:
run_command(cmd)
if __name__ == "__main__":
main()
As you can see, the code is pretty simple. All that it makes is:
- runs commands one by one
- checks exit codes for each command
- prints report using logger
Example output:
INFO: Starting script
INFO: Trying to run command: df -h
INFO: Exit code: 0
INFO: SUCCESS: df -h
INFO: Trying to run command: hostname
INFO: Exit code: 0
INFO: SUCCESS: hostname
INFO: Trying to run command: ping 8.8.8.8 -c 1
INFO: Exit code: 0
INFO: SUCCESS: ping 8.8.8.8 -c 1
INFO: Trying to run command: cp /etc/no/such/file /tmp/
INFO: Exit code: 1
ERROR: FAILURE: cp /etc/no/such/file /tmp/
ERROR: STDERR: cp: /etc/no/such/file: No such file or directory
Just a short example, but it might come in handy as part of a bigger script for everyday sysadmin work.
✅ Content reviewed as of 19 June 2025
Written on August 8, 2017