2016-04-29 89 views
2

我目前正在創建一個類,以在使用ssh(paramiko)的Linux機器上遠程執行命令。以下是我使用在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一個」代碼:「文件中存在錯誤」遇到,我該如何處理它。我嘗試使用channel.recv(buff_size),但這裏的問題是我無法區分錯誤和正常消息。

在此先感謝

回答

1

channel.recv_exit_status()可以用來獲得執行的命令的返回碼。您可以參考this paramiko文檔。