matz_ch
matz_ch

Reputation: 29

How do I get exit code after exec_command?

I have a program that runs from my local computer and connects via SSH (paramiko package) to a Linux computer. I use the following functions to send a command and get an exit_code to make sure it's done.

For some reason, sometimes an exit code is returned, whereas sometimes the code enters an endless loop. Does anyone know why this happens and how to make it stable?

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()}')

Upvotes: 2

Views: 1806

Answers (1)

oBit91
oBit91

Reputation: 398

In case you're using Python version >= 3.6, I advise working with an asynchronous library, that provides await capabilities for optimized run times and more manageable simple code.

For example, you can use asyncssh library that comes with python and does the job as requested. In general writing async code that uses sleeps to wait for a task to be executed should be replaced like so.

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))

You can find further documentation here: asyncssh

Upvotes: 1

Related Questions