为什么$ expect_out(缓冲区)为空?

时间:2015-09-23 19:56:10

标签: unix tcl expect

有没有人知道为什么期望变量$ expect_out(buffer)对于以下代码为空?

有几个SO线程说它应该包含最后一个send命令的输出。那么为什么变量为空?

以下示例:

#!/bin/expect

spawn ssh $MY_NODE

# Logs in
# Does stuff

expect "$"
send "$MY_COMMAND\r" # Prints i7
puts $expect_out(buffer)  # Empty, even though it should clearly be i7

1 个答案:

答案 0 :(得分:2)

基本上,Expect将使用两个可行的命令,例如sendexpect。如果使用send,则必须在之后拥有expect(在大多数情况下)。 (反之亦然,不要求是强制性的)

这是因为没有它,我们将错过生成过程中发生的事情,因为期望您只需要发送一个字符串值而不期望会话中的任何其他内容。

因此,在您的情况下,您在发送命令后错过了添加expect语句。数组expect_out将使用缓冲内容进行更新,但前提是它需要某些输出。

注意:您已使用expect "$"。我猜你试图匹配文字美元符号。这与文字美元符号不匹配,而是指定行尾。它应该用作expect "\\\$"

send "$MY_COMMAND\r"
expect "\\\$"

<强> checkExpectBuffer.exp

#!/usr/bin/expect
#This is a common approach for few known prompts
set prompt "#|%|>|\\\$"; # We escaped the `$` symbol with backslash to match literal '$'

set hostname xxx.xxx.xx.xx
set user dinesh
set password welcome!2E
spawn ssh $user@$hostname
expect "password:"
send "$password\r";
expect -re $prompt; # Matching the prompt with regexp
send "echo i7\r"; # I'm just echoing the value 'i7'
# Comment the below line and run the code, you won't see 'echo i7' command 
# as well as the output of it in 'expect_out(buffer)'
expect -re $prompt 
puts "\n-->$expect_out(buffer)<--"