简体   繁体   中英

How can I handle error while executing remote command in linux

I am currently creating a class to execute command remotely on a linux machine using ssh(paramiko). The following is the code I am using

def connect(self):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(self.ip, port=self.port, username=self.user,password=self.password,timeout=self.timeout)
    time.sleep(10)
    return ssh

def runCommands(self,commands):
    ssh=self.connect()
    channel = ssh.invoke_shell()
    time.sleep(10)
    for command in commands:
        wait=0
        while channel.send_ready()!=True:
            wait+=1
            time.sleep(self.timeout)
            if wait==5:
                return 0
        channel.send(command+'\n')
    channel.send("exit\n")
    return 1

My question here is if the command run into an error for example if I use 'mkdir a': "file exist error" is encountered, How can I handle it. I tried using channel.recv(buff_size) but the problem here is I could not differentiate between error and normal messages.

Thanks in advance

channel.recv_exit_status() can be used to get the return code of the command executed. You can refer to this paramiko documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM