Linux

檢查期望輸出中的單詞並將其添加到文本文件中

  • March 2, 2017

我有這樣的程式碼:

#!/opt/tools/unsupported/expect-5.39/bin/expect

set timeout 10
match_max 256
log_file report.txt

expect_after eof {exit 0}
spawn ssh -l user ip

expect "(yes/no)?" { send "yes\r" }
expect "password:" { send "password\r" }

expect "~]#" { send "date\r" }

set timeout 600

expect "~]#" { send "scp user@ip:/sometlink/AMM.tar.gz /somelink/\r" }

expect "Password:" { send "password\r" }
sleep 5

set timeout 3600

expect "~]#" { send "swadm install import AMM\r" }
sleep 5

expect "~]#" { send "swadm install apply AMM\r" }

expect "~]#" { send "swadm install show AMM\r"}

expect -re "(.*)\r\nproduct-state=(.*)"

foreach line [split $expect_out(1,string) \n] {
       if {[string match *Applied* $line]} {
           send_log "Product install of AMM ----------------------------- Passed"
                   }
   else {
          send_log "Product install of AMM ----------------------------- Failed"
           }
}


expect "~]#" { send "date\r" }
expect "~]#" { send "exit\r" }

它應該檢查 swadm install show AMM 的輸出

product-id=AMM
product-name=Application Manager
product-version=1.0.0
product-state=Applied
product-description=
NCL-list=AMMLV010

如果找到 Applied 單詞,則將安裝成功添加到測試文件中,如果沒有,則添加失敗。但它給了我其他部分的錯誤

invalid command name "else"
    while executing
"else {
          send_log "Product install of AMM -----------------------------     Failed"

("foreach" body line 6)
invoked from within
"foreach line [split $expect_out(1,string) \n] {
   if {[string match *Applied* $line]} {
           send_log "Product install of AMM-----..."

我會這樣做:

expect "~]#" { send "swadm install show AMM\r"}
expect "~]#" {
   if {[string match {*product-state=Applied*} $expect_out(buffer)]} {
       do-thing-1
   } else {
       do-thing-2
   }
}

在“show”命令之後,只需等待下一個提示。然後,期望看到的所有內容都在 中expect_out(buffer),您可以在整個緩衝區文本上使用字元串匹配(或如果需要,也可以使用正則表達式匹配)。您不需要按行拆分它。

我發現了問題!它應該是 } else { 之間沒有新行。

引用自:https://unix.stackexchange.com/questions/348713