Expect

退出 Expect 腳本

  • December 11, 2020

我有這個expect腳本,它將登錄到主機,執行命令,返回它的內容並退出。當我完成執行我的命令時,需要進行什麼樣的清理/正確退出?這個命令總是會返回一些東西,我認為我應該處理的更大的問題是 SSH 掛起,或者以管理員使用者身份登錄掛起。我想我可能一直在處理這個問題timeout,但我不確定:

#!/usr/bin/expect -f

set timeout 10
match_max 100000
set hostname [lindex $argv 0]

spawn /usr/bin/ssh -o "StrictHostKeyChecking no" admin@$hostname
expect "*password:"
send -- "redactedSSHpassword\r"
expect "Username:"
send -- "admin\r"
expect "*password:"
send -- "redacted\r"
expect -- "*#*"
send -- "show stat summary\r"
expect -- "*#*"

我也不明白退出這個腳本並確保我沒有留下過時的會話的正確方法。

如果超時,則expect語句將失敗,它會繼續執行下一條語句。這可能沒有任何意義,但它確實意味著可能會發生以下情況。

You expect "Username:" and get it.
You send "admin\r", and get back "No such username"
You expect "password:" but don't get it because you got the "No such username" message, so you timeout.
You send "redacted\r" and get back "redacted: no such command" but redacted has been added to the history on the machine.
You expect "*#*" ....

當您的腳本到達末尾時,它將退出。此時,ssh 將重新設置為 PID 1。ssh 將在其標準輸入上檢測 EOF,並將其傳遞並退出。所以你可能不需要任何額外的清理。

如果這是我的腳本,我會寫一個小程序

proc lookfor {pat} {
   expect timeout { send_user "timeout looking for '$pat'\r\n" ; exit } $pat
}

並替換所有呼叫expectwithlookfor以使其在匹配失敗後立即退出。可以使用expect_after或提供簡單的診斷expect_beforelookfor

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