shell腳本須要交互的地方可使用here文檔是實現,可是有些命令卻須要用戶手動去就交互如passwd、scphtml
對自動部署免去用戶交互很痛苦,expect能很好的解決這類問題。nginx
expect的核心是spawn expect send setshell
spawn 調用要執行的命令
expect 等待命令提示信息的出現,也就是捕捉用戶輸入的提示:
send 發送須要交互的值,替代了用戶手動輸入內容
set 設置變量值
interact 執行完成後保持交互狀態,把控制權交給控制檯,這個時候就能夠手工操做了。若是沒有這一句登陸完成後會退出,而不是留在遠程終端上。
expect eof 這個必定要加,與spawn對應表示捕獲終端輸出信息終止,相似於if....endif服務器
expect腳本必須以interact或expect eof結束,執行自動化任務一般expect eof就夠了。ssh
設置expect永不超時
set timeout -1ide
設置expect 300秒超時,若是超過300沒有expect內容出現,則推出
set timeout 300spa
expect編寫語法,expect使用的是tcl語法。orm
一條Tcl命令由空格分割的單詞組成. 其中, 第一個單詞是命令名稱, 其他的是命令參數
cmd arg arg argserver
$符號表明變量的值. 在本例中, 變量名稱是foo.
$foohtm
方括號執行了一個嵌套命令. 例如, 若是你想傳遞一個命令的結果做爲另一個命令的參數, 那麼你使用這個符號
[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 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
scp拷貝文件
#!/usr/bin/expectset timeout 10set 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