【问题标题】:How to store output in a variable while using expect 'send' command如何在使用期望“发送”命令时将输出存储在变量中
【发布时间】:2014-01-19 23:43:46
【问题描述】:

谢谢。

但是需要帐号和密码。所以我必须发送它们,然后发送 ovs-vsctl 命令。

脚本是这样的:

spawn telnet@ip 

expect -re "*login*" {
       send "root"
}

expect -re "password*" {
       send "****"
}

send "ovs-vsctl *******"

我想存储这个命令send "ovs-vsctl ****"的输出,但是很多时候我得到了命令“send "password"”的一些输出,我怎样才能得到send "ovs-vsctl****"的输出。命令send "ovs-vsctl ***的输出是两个字符串,每个字符串占一行。

谢谢。

【问题讨论】:

    标签: tcl output send expect


    【解决方案1】:

    也许:

    log_user 0                   ;# turn off the usual output
    spawn telnet@ip 
    expect -re "*login*"
    send "root\r"
    expect -re "password*"
    send "****\r"
    send "ovs-vsctl *******"
    expect eof
    puts $expect_out(buffer)     ;# print the results of the command
    

    【讨论】:

    • 好点!我没有考虑过使用 log_user。这会在允许“真实”命令输出的同时停止远程回显您自己的命令吗?我的想法是你不能把它分开,但我知道什么……你给了我一些我现在需要尝试的东西。 ;-)
    • 只有在输出相对较小的情况下才会真正起作用。我不记得默认情况下有多少期望缓冲区,但它不是无限的。
    【解决方案2】:

    Expect 使用输入缓冲区,其中包含从交互式应用程序返回的所有内容,这意味着进程输出您的输入(只要它是从远程设备,通常是这种情况)。

    expect 命令用于从输入缓冲区恢复文本。每次找到匹配时,直到匹配结束的缓冲区都会被清除,并保存到 $expect_out(buffer)。实际匹配保存到 $expect_out(0,string)。然后缓冲区会重置。

    您需要做的是将输出与expect 语句相匹配,以获得您想要的。

    在您的情况下,我会在发送密码后匹配远程设备提示,然后在发送命令后再次匹配。这样,最后一次匹配后的缓冲区将保存所需的输出。

    类似的东西:

    [...]
    expect -re "password*" {
           send "****"
    }
    
    expect -re ">"
    
    send "ovs-vsctl *******\r"
    
    expect -re ">"  # Better if you can use a regexp based on your knowledge of device output here - see below
    
    puts $expect_out(buffer)
    

    通过根据您对输出的了解使用正则表达式进行匹配,您应该能够仅提取命令输出而不是回显的命令本身。或者,您可以随时使用regexp 命令在事后执行此操作。

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 2016-09-01
      • 1970-01-01
      相关资源
      最近更新 更多