1

ファイルをgrepし、探している文字列を含む行を返すexpectスクリプトを作成しようとしています。この場合、文字列は端末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]
    }

これは、パテ経由で RHEL サーバーに ssh し、最大化されたパテ ウィンドウでスクリプトを実行すると完全に機能します。ただし、grepコマンドが1行に収まらないようにウィンドウの長さを縮小すると、コードが壊れます! 誰でもこれに対する解決策を考え出すのを手伝ってもらえますか? 私は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 コマンドの出力だけを取得する適切な方法は何ですか? コマンドの出力が画面に表示される方法に基づいて、異なる動作を期待するのは非常に奇妙です。どんな助けでも大歓迎です。

4

1 に答える 1