在面對interactive program時 (像login) , 我們常需要等待對方訊息 , 然後再進行input,

(像輸入帳號 , 密碼)

而Expect scripting language則可以幫我們解決這樣的一個問題 , 

在expect中 , 主要有3種command可以利用:

send – to send the strings to the process

expect – wait for the specific string from the process

spawn – to start the command

expect command可以幫我們設定預計對方所會進行的回應 , 

而send將會根據這樣的回應傳送相對應的message .

以下是一個藉由ssh指令自動登入的例子:

#!/usr/bin/expect

set timeout 20

set ip [lindex $argv 0]

set user [lindex $argv 1]

set password [lindex $argv 2]

spawn ssh "$user\@$ip"

expect "Password:"

send "$password\r";

interact

首先我們會藉由spawn執行ssh的指令 , 並等待對方的program要我們輸入password的訊息 ,

而當我們expect到這樣的訊息之後 , 便會send該帳號所需要的password來進行login.

 

ref : http://www.thegeekstuff.com/2010/10/expect-examples/

相关文章