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

标签 python ssh paramiko

我目前正在创建一个类来使用 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文档。

关于python - 在 linux 中执行远程命令时如何处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36934413/

相关文章:

python - 如何修复: compairing result of a bigquery query to a list

ssh - 如何使用 terraform 向 GCP 实例添加 ssh key ?

linux - 如何从 azure 自动化证书中获取公钥

python - paramiko 中的管道命令

python - 如何使用 paramiko 通过键盘身份验证

python - Ubuntu Python "No module named paramiko"

python - 在 python 上通过互联网读取文本文件

python - 就地修改 Python 列表

python - 属性错误 : 'module' object has no attribute 'scandir'

netbeans - Netbeans:通过SSH使用/源文件的远程项目?