在Expect中获取远程脚本的结果

时间:2016-05-13 10:56:15

标签: expect

我执行远程脚本并检查脚本的返回状态,但是如果我按以下方式执行,则返回密码的状态,但不返回被调用脚本的状态。如何获取被调用脚本的返回状态。请提前帮助谢谢。

#!/usr/bin/expect
proc auto { } {
global argv
set timeout 120
set ip XXXX.XXX.XX.XX
set user name
set password pass
set ssh_opts {-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no}
set script /path-to-script/test.sh
spawn ssh {*}$ssh_opts $user@$ip bash $script {*}$argv
expect "Password:"
send "$password\r"
send "echo $?\r"
expect {
  "0\r" { puts "Test passed."; }
  timeout { puts "Test failed."; }
}
expect eof
}
auto {*}$argv

1 个答案:

答案 0 :(得分:1)

您自动ssh bash remote_script,因此您无法获得shell提示,echo $? - ssh将启动您的脚本,然后退出。

您需要做的是获取生成进程的退出状态(ssh应该以远程命令的退出状态退出)。 expect' wait命令可以获取退出状态(以及其他信息)

spawn ssh {*}$ssh_opts $user@$ip bash $script {*}$argv
expect {
    "Password:" { send "$password\r"; exp_continue }
    timeout     { puts "Test failed." }
    eof
}

# ssh command is now finished
exp_close
set info [wait]
# [lindex $info 0] is the PID of the ssh process
# [lindex $info 1] is the spawn id
# [lindex $info 2] is the success/failure indicator
if {[lindex $info 2] == 0} {
    puts "exit status = [lindex $info 3]"
} else {
    puts "error code = [lindex $info 3]"
}