標籤:
FROM:http://www.nginx.cn/1934.html
shell指令碼需要互動的地方可以使用here文檔是實現,但是有些命令卻需要使用者手動去就互動如passwd、scp
對自動部署免去使用者互動很痛苦,expect能很好的解決這類問題。
expect的核心是spawn expect send set
spawn 調用要執行的命令
expect 等待命令提示資訊的出現,也就是捕捉使用者輸入的提示:
send 發送需要互動的值,替代了使用者手動輸入內容
set 設定變數值
interact 執行完成後保持互動狀態,把控制權交給控制台,這個時候就可以手工操作了。如果沒有這一句登入完成後會退出,而不是留在遠程終端上。
expect eof 這個一定要加,與spawn對應表示捕獲終端輸出資訊終止,類似於if....endif
expect指令碼必須以interact或expect eof結束,執行自動化任務通常expect eof就夠了。
設定expect永不逾時
set timeout -1
設定expect 300秒逾時,如果超過300沒有expect內容出現,則推出
set timeout 300
expect編寫文法,expect使用的是tcl文法。
一條Tcl命令由空格分割的單片語成. 其中, 第一個單詞是命令名稱, 其餘的是命令參數
cmd arg arg arg
$符號代表變數的值. 在本例中, 變數名稱是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 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 [email protected]$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
[轉載]使用expect實現shell自動互動