Search code examples
pythonlinuxsshpexpectqnx

How to make remotely executed pexpect spawn FULLY WAIT for a command to resolve before continuing?


I am using pexpect to connect to a remote computer running QNX, upload an exectuable, run the executable, then bring results back to my local machine.

My problem is this: the commands are executed fine, but I lose all logged results because the process returns to me as soon as I execute the command to run my application (let's call it ./application), a C++ executable. What I need to do is have the process wait until the command has completely finished running before proceeding any further.

I've tried utilizing proc.wait() to no avail, my best guess is that it's because the proc is the SSH session, not the process launched by running ./application. I've tried proc.expect("bash-username$") and similar, only to find that the application returns immediately still.

The code is fairly simple and straightforward, but it's not expecting exactly as I'd hope it would. Here's an example of how I'm conducting the operation:

// This section all works fine.  Establish SSH and expect Last Login info

ssh_cmd = ssh_cmd = "ssh " + self.user + "@" + self.hostname
self.proc = pexpect.spawn(ssh_cmd)
self.proc.expect("Last login", timeout = 5)
print("SSH login successful!")
self.is_connected = True

// Problems are here.  Outside scope executes a command now by calling this:
// Let's say the command here is Sleep 5.  Or an executable ./application  
//The Pexpect below SHOULD wait until it finishes executing, but it 
doesn't Sleep for 5 seconds or wait for ./application, this expect 
line returns IMMEDIATELY every time. 

def execute_command(self, command):
    if self._is_connected:
        self.proc.sendline("command")
        self.proc.expect("username:/")

So essentially every time that runs, it immediately continues to the next portion of code after the function executes the command, seemingly not caring about the proc.expect. Am I utilizing this incorrectly? How can I get the process to wait until the commands are ACTUALLY finished executing, not just send the line and return immediately?


Solution

  • I found a solution to my own problem, utilizing the subprocess module instead of pexpect.

    Solution is to call subprocess.Popen for SSH with a command variable as follows:

    command_as_string = '/home/user/applicationExecutable'
    ssh = subprocess.Popen(['ssh', '-t', 'username@hostname',
                            command_as_string'],
                                       stderr=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       shell=False,
                                       universal_newlines=True,
                                       bufsize=0
                                       )
    

    It will wait until the command resolves before disconnecting and continues the rest of the Python file as expected.