Expect return code

Hello everyone
Can some help me with understand return code in expect

#!/usr/bin/expect

set timeout  1

set SRV [lindex $argv 0]
set user [lindex $argv 1]
set pw [lindex $argv 2]

spawn ssh $user@$SRV
expect {
        "(yes/no)? " { send "yes\r" ; exp_continue }
        "assword: " { send "$pw\r" ; exp_continue }
        eof
}

expect "$ "
send "sudo su - root\r"
expect "word:"
send "$pw\r"
expect "# "
send "ps -ef | grep -i sendmail | grep -v grep\r"
expect "# "
set retcode $?

if { $retcode != 0} {
    puts "False : $retcode\n";
} else {
    puts "Success : $retcode\n";
}

exit

I wrote this code to check if sendmail is running, but part with return code is not working.

Hi,

I think the problem here (though I'm far from an expect expert, or indeed a regular user of it) is that the $? variable is a bash feature, and not an expect one. That's not how you capture exit values in expect .

So what's actually happening here is that your variable retcode is becoming equal to, quite literally, the string $? . And that's why your comparison fails later on.

I believe to capture exit values in expect you have to use the wait command to hang about and wait for your sent command to exit, and to capture information relating to how it exited, including among other things its exit value. You could then do a comparison on the information obtained by wait (the fourth value returned by it is I believe the exit value of the last process executed) and do your check that way.

Hope this helps.

I would politely suggest that expect is not the solution to your problem. If you are trying to automate login or sudo use, you should use the correct tools. For login with ssh, use SSH-keys. For sudo use, write the appropriate sudo rules that do not require a password.

You are probably over-complicating things by assuming that tools must talk to a user and that expect is your way to pretend to be that user.

The ps command should not need super-user privilege to run. What are you actually trying to achieve?

Kind regards,
Robin