shell腳本需要交互的地方可以使用here文檔是實現,但是有些命令卻需要用戶手動去就交互如passwd、scp,對自動部署免去用戶交互很痛苦,expect能很好的解決這類問題。
expect的核心是 spawn expect send set
spawn 調用要執行的命令等待命令提示信息的出現,也就是捕捉用戶輸入的提示:
send 發送需要交互的值,替代了用戶手動輸入內容
set 設置變量值
interact 執行完成后保持交互狀態,把控制權交給控制台,這個時候就可以手工操作了。如果沒有這一句登錄完成后會退出,而不是留在遠程終端上。
expect eof 這個一定要加,與spawn對應表示捕獲終端輸出信息終止,類似於if....endif
expect 腳本必須以interact或expect eof結束,執行自動化任務通常expect eof就夠了。
set timeout -1 設置expect永不超時
set timeout 300 設置expect 300秒超時,如果超過300沒有expect內容出現,則退出
expect編寫語法,expect使用的是tcl語法。
cmd arg arg arg 一條Tcl命令由空格分割的單詞組成. 其中, 第一個單詞是命令名稱, 其余的是命令參數
$foo $符號代表變量的值. 在本例中, 變量名稱是foo.
[cmd arg] 方括號執行了一個嵌套命令. 例如, 如果你想傳遞一個命令的結果作為另外一個命令的參數, 那么你使用這個符號
"some stuff" 雙引號把詞組標記為命令的一個參數. "$"符號和方括號在雙引號內仍被解釋
{some stuff} 大括號也把詞組標記為命令的一個參數. 但是, 其他符號在大括號內不被解釋
反斜線符號是用來引用特殊符號. 例如:\n 代表換行. 反斜線符號也被用來關閉"$"符號, 引號,方括號和大括號的特殊含義
expect使用實例
1、首先確認expect的包要安置。
#rpm -qa | grep expect
如果沒有則需要下載安裝,
#yum install expect
2、安裝完成后,查看expect的路徑,可以用
#which expect
/usr/bin/expect
3、編輯腳本
#vi autosu.sh
添加如下內容
#!/usr/bin/expect -f //這個expect的路徑就是用which expect 查看的結果
spawn su - nginx //切換用戶
expect "password:" //提示讓輸入密碼
send "test\r" //輸入nginx的密碼
interact //操作完成
4.確定腳本有可執行權限
chmod +x autosu.sh
5.執行腳本 ** expect autosu.sh** 或 ** ./autosu.sh**
expect常用腳本
登陸到遠程服務器
#!/usr/bin/expect -f
set timeout 5
set server [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
spawn ssh -l $user $server
expect {
"(yes/no)" { send "yes\r"; exp_continue }
"password:" { send "$passwd\r" }
}
expect "*Last login*" interact <br />
scp拷貝文件
#!/usr/bin/expect -f
set timeout 10
set host [lindex $argv 0] //第1個參數,其它2,3,4參數類似
set username [lindex $argv 1]
set password [lindex $argv 2]
set src_file [lindex $argv 3]
set dest_file [lindex $argv 4]
spawn scp $src_file $username@$host:$dest_file
expect {
"(yes/no)?"{
send "yes\n"
expect "*assword:" { send "$password\n"}
}
"*assword:"{
send "$password\n"
}
}
expect "100%"
expect eof
使用方法
./expect_scp 192.168.75.130 root 123456 /root/src_file /root/dest_file
以上的命令執行后,將把本地/root目錄下的src_file文件拷貝到用戶名為root,密碼為123456的主機192.168.75.130中的/root下,同時還將這個源文件重命名為dest_file