如何在 exec_command 之后获取退出代码?

How do I get exit code after exec_command?

我有一个从本地计算机运行并通过 SSH(paramiko 软件包)连接到 Linux 计算机的程序。 我使用以下函数发送命令并获取 exit_code 以确保它已完成。

由于某些原因,有时会返回退出代码,而有时代码会进入死循环。 有谁知道为什么会发生这种情况以及如何使其稳定?

def check_on_command(self, stdin, stdout, stderr):
    if stdout is None:
        raise Exception("Tried to check command before it was ready")
    if not stdout.channel.exit_status_ready():
        return None
    else:
        return stdout.channel.recv_exit_status()

def run_command(self, command):
    (stdin, stdout, stderr) = self.client.exec_command(command)
    logger.info(f"Excute command: {command}")
    while self.check_on_command(stdin, stdout, stderr) is None:
        time.sleep(5)
    logger.info(f'Finish running, exit code: {stdout.channel.recv_exit_status()}')

如果您使用的是 Python 版本 >= 3.6,我建议使用异步库,它提供优化 运行 时间的等待功能和更易于管理的简单代码。

例如,您可以使用 python 附带的 asyncssh 库并按要求完成工作。通常编写使用睡眠等待任务执行的异步代码应该像这样替换。

import asyncio, asyncssh, sys

async def run_client():
    async with asyncssh.connect('localhost') as conn:
        result = await conn.run('ls abc')

        if result.exit_status == 0:
            print(result.stdout, end='')
        else:
            print(result.stderr, end='', file=sys.stderr)
            print('Program exited with status %d' % result.exit_status,
                  file=sys.stderr)

try:
    asyncio.get_event_loop().run_until_complete(run_client())
except (OSError, asyncssh.Error) as exc:
    sys.exit('SSH connection failed: ' + str(exc))

您可以在此处找到更多文档:asyncssh