Search code examples
pythonsshexpect

Returning status of grep command executed remotely via ssh embedded in expect command inside python


I have a below python script where in I am executing a remote SSH command using expect. Here, even the target file contains the string "error" or not, the exit code is returned as success always as the ssh connectivity is what only checked. How can I get the status of the grep command?

#! /usr/bin/python

import subprocess

def execute(cmd):
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    _output, _error = proc.communicate()
    _code = proc.returncode
    return _output, _error, _code

host = "localhost"
passwd = "kube"

cmd="/usr/bin/expect -c 'spawn ssh "+host+" \"cat /home/kube/f1 | grep -qi error\"; expect \"password:\" { send \""+passwd+"\r\"} ;interact' "
_output, _error, return_code = execute(cmd)
print cmd + "\n" + _output + "\n" + _error

if (return_code == 0):
    print "no error"
else:
    print "contains error"

Solution

  • Option 1:

    Let the remote command output something which indicates success/failure for you. E.g.:

    ssh user@host "/some/command | grep -q some-string && echo MAGIC-SUCCESS || echo MAGIC-FAILURE"
    

    And in Python you can get the output and parse it.

    Option 2:

    According to man expect:

    • wait [args]

      [...] wait normally returns a list of four integers. The first integer is the pid of the process that was waited upon. The second integer is the corresponding spawn id. The third integer is -1 if an operating system error occurred, or 0 otherwise. If the third integer was 0, the fourth integer is the status returned by the spawned process. If the third integer was -1, the fourth integer is the value of errno set by the operating system. [...]

    So your Expect code can check the wait result and then exit with different values and Python code can get the exit status.

    For Expect part it's like this:

    spawn ...
    ...
    expect eof
    set result [wait]
    exit [lindex $result 3]