#!/usr/bin/expect
spawn ssh [email protected]
expect {
*(yes/no)?" {send "yes\r"}
"*Password:" { send "123456\r"}
}
expect ":~#"
send "rpm -qa|grep net-snmp\r"
send "ret=`echo $?`\r"
send “exit $ret”
expect eof
执行脚本,提示can't read "ret":no such variable,不知如何在expect中定义ret
可这样,终端结果显示ret=`echo $?` ......exit $ret,值完全没有赋进去,还请帮忙
追答值当然已经付了,在远端的 shell 进程里, ret 的值已经有了,如果你要打印出来,也必须在远端打印,比如
send "rpm -qa|grep net-snmpv\r"
send "ret=`echo $?`\r"
send "echo I will exit by ret=\$ret\r"
send "exit \$ret\r"
expect eof
你应该能看到显示
I will exit by ret=0
之类的东西。
恩,是的,但是假如ret值是1,我exit 1退出返回到主程序为什么,不行呢?【这个expect是个单独的脚本】
主程序调用判断部分为:
./expect
if [ $? -eq 0 ]; then ......
为什么无论expect中ret值为0或1,都执行0=0?不是expect中执行exit 1,返回应该也是1么?
我已经说了, ret 不是 expect 中的变量,而是远程 shell 进程里的变量,expect 根本不知道 ret 的值。并且你expect脚本并没有指定返回值,默认就永远是0。
如果你是想让 expect 根据远程进程的返回值做出相应的返回,必须用复杂一点的方法:
send "rpm -qa|grep net-snmpv\r"
send "ret=`echo $?`\r"
send "echo I will exit by ret=\$ret\r"
send "exit \$ret\r"
expect eof
set my_ret [wait]
send_user "spawned process returned [lindex $my_ret 3]\r"
exit [lindex $my_ret 3]
具体细节,你需要了解一些 Tcl 和 expect的知识。