gameveloster
gameveloster

Reputation: 1523

Get Netmiko script wait till command has finished running

I'm using netmiko to SSH into an Ubuntu machine to run a Python script that takes a few minutes to finish running. The Python script does not write anything to stdout until just before it has finished running.

However, the current implementation appears to be terminating the SSH connection early thinking that the Python script has already finished running when it has not.

What is a good way to wait till the Python script has completed running (including having crashed with an exception) before closing the SSH connection.

from netmiko import ConnectHandler
import time

device = {
    "device_type": "linux",
    # ...    
}

with ConnectHandler(**device) as ssh:
    ssh.write_channel("python slow_task.py\n")
    outputs = []
    while True:
        time.sleep(10)
        output = ssh.read_channel()
        if not output:
            break
        print(output.strip())
        outputs.append(output)

Upvotes: 1

Views: 693

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202534

I have no experience with Netmiko. All I know that it is a library built on top of Paramiko.

In Paramiko, if you want to execute command and wait for it to complete, you use "exec" channel, which lasts only as long as the command does. So you read the output until the channel closes.

I believe that Netmiko hides the "exec" channel API (but I'm not sure) and offers only the "shell" API. That's imo a wrong design. See also What is the difference between exec_command and send with invoke_shell() on Paramiko?

If my understanding is correct and you have to work with the "shell" API, you have to use shell features, to find out when the command finishes. You can solve that by printing a unique separator (string) after the command and wait for it to appear in the output stream.

ssh.write_channel("python slow_task.py && echo unique-string-separating-output-of-the-commands\n")

Upvotes: 1

Related Questions