Expect是一個用于自動化交互式應用程序的工具,如登錄、文件傳輸等
spawn
命令啟動交互式程序:spawn <command>
例如,要啟動SSH會話,可以使用:
spawn ssh user@example.com
expect
命令等待特定的字符串出現:expect "<string>"
當Expect腳本檢測到指定的字符串時,它將自動發送相應的命令。例如,要等待SSH登錄提示符(通常是$
或%
),可以使用:
expect "$"
send
命令發送命令到交互式程序:send "<command>\r"
\r
是回車符,用于模擬用戶按下Enter鍵。例如,要輸入用戶名,可以使用:
send "username\r"
interact
命令進入交互模式:interact
在交互模式下,用戶可以直接與交互式程序進行交互,而無需腳本干預。要退出交互模式,可以按Ctrl+C
兩次。
close
命令關閉當前交互式程序:close
lindex
命令:set output [lindex $expect_out(buffer) 0]
要循環處理輸出,可以使用while
循環:
while {$output ne ""} {
# 處理輸出的邏輯
set output [lindex $expect_out(buffer) 0]
}
這是一個簡單的Expect腳本示例,用于自動登錄SSH服務器并執行命令:
#!/usr/bin/expect
set timeout 20
set username [lindex $argv 0]
set password [lindex $argv 1]
set command [lindex $argv 2]
spawn ssh $username@example.com
expect "$ "
send "$password\r"
expect "$ "
send "$command\r"
expect "$ "
interact
要運行此腳本,請將其保存為auto_ssh.exp
,并確保它具有可執行權限(使用chmod +x auto_ssh.exp
)。然后,可以通過以下方式運行腳本:
./auto_ssh.exp username password "command"