expect本身是一個免費的程式設計工具,用來實作自動和互動任務進行通信,而無需人工的幹預,expect則可以根據程式的提示模拟标準輸入提供給程式需要的輸入來實作互動程式執行。比如實作ssh自動登入通常就需要用expect來實作。
[root@shell ~]# which expect #檢視是否安裝
[root@shell ~]# yum -y install expect #安裝
使用執行個體分解:
[root@shell ~/shell]# cat ssh
1 #!/usr/bin/expect
2 set timeout 30
3 set pass "redhat"
4 spawn ssh [email protected]
5 expect "password:"
6 send "$pass\r"
7 interact
分解:
1.告訴shell調用expect來執行
2.設定逾時時間
3.定義密碼變量
4.使用expect内部指令spawn指令來啟動ssh,給ssh運作程序加個殼,用來傳遞互動指令。
5.判斷執行指令後輸出的結果是否有“password:”
6.執行互動動作,輸入密碼,\r代表回車
7.執行完成後保持互動狀态,把控制權交給控制
測試使用:
[root@shell ~/shell]# chmod u+x ssh
[root@shell ~/shell]# ./ssh
spawn ssh [email protected]