寫自動化腳本時最惱人的時刻,莫過於某個指令突然停下來等你輸入。ssh 要帳號密碼、docker-machine 要確認 y/n,腳本走到這裡就卡住,後面的步驟再也跑不完。
如果只是單純的一次性確認,最省事的做法就是把答案用 echo 送進去:
# ... some directives here
# Remove the machine, confirming "y" when asked by docker-machine
echo 'y' | docker-machine rm default
# ... more directives here
這招在「只問一次、且不需要讀取輸出」的場景很好用,但遇到需要連續應答、或要依對方回覆決定下一步的情況,就必須請出 expect。
expect 的核心概念是 spawn 啟動互動程式、expect 等待特定字串、send 送出回應,迴圈下去直到 eof。以下是以 expect 自動化 ssh 登入的範例:
# timeout is a predefined variable in expect, 預設 10 秒
# spawn_id 也是 expect 的預設變數
# 好的習慣是在最後關閉 spawn 產生的 handle
set timeout 60
spawn ssh $user@machine
while {1} {
expect {
eof {break}
"The authenticity of host" {send "yes\r"}
"password:" {send "$password\r"}
"*\]" {send "exit\r"}
}
}
wait
close $spawn_id
同样的模式也適用在 telnet 這類老派協議上,差別只在於提示字元與收尾方式:
# 假設 $remote_server, $my_user_id, $my_password, $my_command 已在前面讀入
# 開啟 telnet 工作階段,等待帳號提示
spawn telnet $remote_server
expect "username:"
send "$my_user_id\r"
expect "password:"
send "$my_password\r"
expect "%"
# 送出要執行的指令,再等一次提示
send "$my_command\r"
expect "%"
# 把輸出擷取到變數,之後可印出或寫檔
set results $expect_out(buffer)
send "exit\r"
expect eof
掌握 spawn/expect/send 這三個動詞,大多數需要互動的指令都能被馴服成非互動流程。