1

我正在尝试创建一个期望脚本,它将 grep 一个文件并返回包含我正在寻找的字符串的行,在这种情况下,该字符串将是一个终端 ID。例如,我有一个名为 terminal_list.txt 的文件,其内容如下:

 0x400 192.168.62.133 10006
 0x420 192.168.62.133 10021
 0x440 192.168.62.133 10022

我希望返回以 0x420 开头的行

我的代码如下:

    #!/usr/bin/expect -f

set terminal_list "/home/linkway/terminal_list.txt"
set termid "0x400"

spawn /bin/bash

expect "] "

    # Get ip and port of terminal
    # Check if termid exists in terminal_list file
    set command "grep -q '$termid' '$terminal_list' && echo 'true' || echo 'false'"
    send "$command\r"
    expect "$command\r\n"
    expect -re "(.*)\r\n.*] "
    set val $expect_out(1,string)
    # If terminal_list does not exist print error and exit
    if { [string first "No such file or directory" $val] >= 0 } {
      puts "$terminal_list does not exist. Script Failed"
      exit
    # If terminal_list does not contain termid print error and continue
    } elseif { [string match "false" $val] } {
      puts "\nTerminal $termid does not exist in ${terminal_list}. Cannot update bootfile.\n"
    # If termid is found in terminal_list, get the ip and port of the terminal
    } else {
      set command "grep '$termid' '$terminal_list'"
      send "$command\r"
      expect "$command\r\n"
      expect -re "(.*)\r\n.*] "
      set val $expect_out(1,string)
      set ip_port [string range $val 6 end]
    }

当我通过 putty SSH 到 RHEL 服务器并在最大化的 putty 窗口中运行脚本时,这非常有效。但是,当我缩小窗口长度以使 grep 命令不再适合单行时,我的代码会中断!谁能帮我想出一个解决方案?我一直在努力处理 expect_out 并且真的可以使用一些指导。

编辑:我发现是什么导致了这个错误。事实证明,当 grep 命令拆分为多行时,会在换行符所在的命令中添加一个 \r。这是来自 exp_internal 1 的一些调试信息。您可以看到如何将 \r 添加到 grep 命令中,该命令运行到下一行:

expect: does "grep -q '0x400' '/home/linkway/term \rinal_list.txt'
&& echo 'true' || echo 'false'\r\n" (spawn_id exp6)
match glob pattern "grep -q '0x400' '/home/linkway/terminal_list.txt'
&& echo 'true' || echo 'false'\r\n"? no

为什么会发生这种情况,获取 grep 命令输出的正确方法是什么?我觉得很奇怪,根据命令输出在屏幕上的显示方式,expect 的行为会有所不同。任何帮助是极大的赞赏。

4

1 回答 1

0

通过使我的脚本更像预期,我能够找到一个更清晰的解决方案来解决我的问题。这是它的样子:

set command "grep -q '$termid' '$terminal_list' && echo 'true' || echo 'false'"
send "$command\r"
expect {
  -re ".*\r\ntrue\r\n.*] " {
    send "grep '$termid' '$terminal_list'\r"
    expect ".*\r\n"
    expect -re "(.*)\r\n.*] "
    set val $expect_out(1,string)
    set ip_port [string range $val 6 end]

    puts "\nUpdating $termid bootfile"
    updatebootfile $ip_port $boot_data $termid
  }
  -re ".*\r\nfalse\r\n.*] " {
    puts "\nTerminal $termid does not exist in ${terminal_list}. Cannot update bootfile.\n"
  }
  -re "No such file or directory.*] " {
    puts "$terminal_list does not exist. Script Failed"
    exit 1
  }
  timeout {
    puts "expect timeout when searching for $termid in $terminal_list"
  }
}
于 2013-07-18T14:12:50.093 回答