Skip to main content
 首页 » 编程设计

python之在 linux 中执行远程命令时如何处理错误

2025年04月02日17langtianya

我目前正在创建一个类来使用 ssh(paramiko) 在 linux 机器上远程执行命令。以下是我使用的代码

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 

我的问题是,如果命令遇到错误,例如如果我使用“mkdir a”:遇到“文件存在错误”,我该如何处理。我尝试使用 channel.recv(buff_size) 但这里的问题是我无法区分错误消息和正常消息。

提前致谢

请您参考如下方法:

channel.recv_exit_status() 可用于获取执行命令的返回码。可以引用this paramiko文档。