Q: paramiko : how to halt script if exit code of command is not successful? I have this script made in python with paramiko
# -*- coding:Utf8 -*-
import sys
import paramiko 
from scp import SCPClient

#Connect function
def createSSHClient(server="ec2-35-180-205-148.eu-west-3.compute.amazonaws.com", port=22, user="admin", key="/home/user/Téléchargements/aws_webforce.pem",password=""):
    "createSSHClient return SSHClient object from paramiko.client class and connect to server on port using user and key"   
    ssh = paramiko.client.SSHClient()
    ssh.load_host_keys(key)
    #ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #to avoid raise SSHException Server XY not found in known_hosts
    ssh.connect(hostname=server,port=port,username=user,key_filename=key)
    return ssh

#Connecting
ssh=createSSHClient()

# Define progress callback that prints the current percentage completed for the file
def progress(filename, size, sent):
    sys.stdout.write("%s's progress: %.2f%%   \r" % (filename, float(sent)/float(size)*100) )

# SCPCLient takes a paramiko transport and progress callback as its arguments.
scp = SCPClient(ssh.get_transport(),progress=progress)

#use scp with python: Uploading the 'corrige_exercice1_docker_compose' directory with its content in the
# /tmp remote directory
scp.put('corrige_exercice1_docker_compose', recursive=True, remote_path='/tmp')
scp.close()


for cmd in ["sudo apt update",
            "sudo apt install docker.io",
            "sudo apt install docker-compose",
            "cd /tmp/corrige_exercice1_docker_compose && sudo docker-compose up -d",
            "echo 'done'"]:
    stdin, stdout, stderr = ssh.exec_command(cmd)
    stdout_list=stdout.readlines()
    for txt in stdout_list:    
        print(txt)

ssh.close()

I first didnt do cd /tmp && and ran cd /tmp in a separate command. The docker-compose didnt run correctly (i didnt have it running on the server).
However, my paramiko script didnt halt or showed an error for this command.
How can i set paramiko to halt on exit code of command not 0 ?
I have tried to check the doc @ https://docs.paramiko.org/en/stable/api/client.html but didnt find.
thank you

A: You can have the return code of the executed command from stdout and stop the loop if it is greater than 0:
for cmd in list_of_cmds:
    stdin, stdout, stderr = ssh.exec_command(cmd)
    return_code = stdout.channel.recv_exit_status()
    if return_code > 0:
        print(f"Command '{cmd}' was not successful")
        break

