2014-11-04 46 views
0

我使用下面的原始代码来初始化连接到设备,运行一些命令并将值存储到变量'op'以便我可以解析它,但看起来就像事实上尽管commad远程执行变量op没有设置。我也尝试打印expcet缓冲区的值,但它没有命令o/p的值。这里出了什么问题?通过ssh捕获输出为一个变量用于运行命令

spawn /usr/bin/ssh [email protected][lindex $argv 0] 
    expect { 
     -re ".*Are.*.*yes.*no.*" { 
     send "yes\n" 
     exp_continue 
     #look for the password prompt 
     } 

     "*?assword:*" { 
     send "$password\r" 
     expect "#" 
     send "\n" 
     } 

    } 

    set op [split [send "$cmd\r"]] 
    set op $expect_out(buffer); 

回答

0

问题是因为下面的代码。

set op [split [send "$cmd\r"]]; # 'send' command won't return the 'cmd' output. 

发送命令后,你必须给下一expect语句,则只能期待将等待它反过来会被保存到expect_out(buffer)

你要发送命令并等待提示如下。

send "$cmd\r" 
expect "#" 
puts $expect_out(buffer); #Will print the output of the 'cmd' output now. 
set op [ split $expect_out(buffer) ] 

这是因为没有send后,多了一个expect,我们将错过了什么衍生的SSH会话expect正在发生的事情会认为你只需要发送一个字符串值,而不是从期待别的会话。

请记住,使用split而没有任何第二个参数会导致输出分裂white-space

执行该命令后要等待的单词可能因您的系统而异。它可以是#$>:;所以,确保你给出了正确的一个。或者,您可以在发送指令后使用expect提供对提示的广义化这样

set prompt "#|>|:|\\\$"; # We escaped the `$` symbol with backslash to match literal '$' 

,它可以被用来作为

expect -re $prompt; #Using regex to match the pattern 

更新:

也许,#的匹配已经在预期缓冲区中可用,从而导致出现这个问题。为了避免这种情况,您可以在发送命令之前尝试在代码中添加以下行。

expect * 
send "$cmd\r" 
expect "#" 
puts $expect_out(buffer); #This should have the output of the command executed. 

在这里,*匹配任何东西。这就像是说:“我不在乎输入缓冲区中的 ,把它扔掉。”如果没有任何内容,这种模式总是匹配,即使是 。请记住*匹配任何内容,并且空的 字符串就是任何东西!作为这种行为的必然结果,该命令 总是立即返回。它从不等待新数据到达。它不需要,因为它匹配所有的东西。

+0

仍然不起作用,expect_out缓冲区似乎没有整个输出。我尝试将matc_max设置为100000,但无济于事。 – Zuckerberg 2014-11-05 20:55:11