標籤:
expect 是由 Don Libes 基於 Tcl 語言開發並廣泛用於互動式操作和自動化測試情境中,通過 expect 可以讓 shell指令碼無需人為幹預自動進行互動式通訊。
expect 的核心功能是根據設定好的匹配形式,以執行相匹配的動作,進入自動化的人機互動。
以下以Ubantu上Demo做案例說明:
sudo apt-get install expect
以 SSH 登陸本機在$HOME下建立kitty檔案夾作為例子,下面是 shell指令碼源碼。
#!/usr/bin/expect -f
set timeout 30set param1 [lindex $argv 0]spawn ssh -p 222 [email protected]127.0.0.1expect { "(yes/no)?" {send "yes\r";exp_continue}}
expect "password:"send "a123456\r"
expect "@"send "cd /home/genter\r"
expect "@"send "mkdir $param1\r"
expect "@"send "exit\r"expect eof
[#!/usr/bin/expect -f]:告訴作業系統該指令碼代碼使用 expect 執行
[set timeout 30]:逾時時間,單位:秒。逾時指令碼將自動向下執行
[set param1 [lindex $argv 0]]:接收執行shell指令碼時傳入的參數,參數依次為:$argv 0, 1, 2...
[spawn ssh -p 222 [email protected]]:進行ssh登陸,expect使用 spawn啟動指令碼和命令會話,這裡啟動 ssh命令(ssh命令將以子進程方式產生)
[expect {"(yes/no)?" {send "yes\r";exp_continue}}]:expect命令用於判斷上次執行命令的結果中是否包含某字串,exp_continue表示繼續執行下面的匹配
[expect "password:" send "a123456\r"] :send命令用於執行互動動作,與人工輸入密碼一樣
將上面指令碼儲存並賦執行許可權,執行過程如下:
": no such file or directory :shell指令碼中在windows下編輯的,使用了windows中分行符號導致。切記:在linux中編輯shell指令碼
interact:執行完後保持互動狀態,將控制權交給控制台以進行人工操作,如果沒有這個命令執行完後會自動結束。
補充說明:
1、expect執行速度較慢,如自動輸入密碼時需要等待一小段時間。
2、shell指令碼需用 ./指令碼名 執行,不能用 sh 指令碼名,因為 expect 不是用bash執行
Linux 中使用 expect