轉載from:https://blog.csdn.net/robertsong2004/article/details/38983259
本文譯至:http://www.thegeekstuff.com/2010/10/expect-examples/
Expect 腳本語言用於自動提交輸入到交互程序。它相比其它腳本語言簡單易學。使用expect腳本的系統管理員和開發人員可以輕鬆地自動化冗餘任務。它的工作原理是等待特定字符串,併發送或響應相應的字符串。
以下三個expect命令用於任何自動化互動的過程。
- send – 發送字符串到進程
- expect – 等待來自進程的特定的字符串
- spawn – 啓動命令
請確保在您的系統上安裝expect軟件包,因爲它不會被默認安裝。 一旦安裝後,你會看到expect解釋器“/usr/bin/expect”。 一般來說,expect腳本文件具有.exp的擴展。
1. Expect “Hello World”範例
下面的expect腳本等待具體字符串“hello”。 當它找到它時(在用戶輸入後),“world”字符串將作爲應答發送。
#!/usr/bin/expect expect "hello" send "world"
2. 等待的字符串超時
默認情況下,等待的超時時間爲10秒。 如果你不爲expect命令輸入任何東西,將在20秒內超時。 您也可以更改超時時間,如下所示。
#!/usr/bin/expect set timeout 10 expect "hello" send "world"
3. 使用Expect自動化用戶進程
在Expect的幫助下,你可以自動化用戶進程,並得到期望的輸出。 例如,您可以使用Expect編寫測試腳本來簡化項目的測試用例。
下面的例子執行了額外的程序自動化。
#!/usr/bin/expect set timeout 20 spawn "./addition.pl" expect "Enter the number1 :" { send "12\r" } expect "Enter the number2 :" { send "23\r" } interact
執行上面的腳本,輸出結果如下所示。
$ ./user_proc.exp spawn ./addition.pl Enter the number1 : 12 Enter the number2 : 23 Result : 35
如果你寫的代碼沒有interact命令,在這種情況下,腳本會在發送字符串“23\r”後立即退出。 interact命令執行控制,處理addtion進程的作業,並生成預期的結果。
4. 在$expect_out變量中的匹配和不匹配的內容
在字符串匹配成功時expect返回,但在此之前它將匹配的字符串存儲在$expect_out(0,string)。之前所收到的字符串加上匹配的字符串存儲在$expect_out(buffer)。下面的例子展示了這兩個變量匹配的值。
#!/usr/bin/expect set timeout 20 spawn "./hello.pl" expect "hello" send "no match : <$expect_out(buffer)> \n" send "match : <$expect_out(0,string)>\n" interact
hello.pl程序只是打印兩行,如下圖所示。
#!/usr/bin/perl print "Perl program\n"; print "hello world\n";
如下所示執行。
$ ./match.exp spawn ./hello.pl Perl program hello world no match : <Perl program hello> match : <hello>
5. 自動化SU登錄到其他用戶帳戶
Expect可以讓你從程序中傳遞密碼給Linux登錄賬號,而不是在終端輸入密碼。在下面的程序中,su自動登錄到需要的賬戶上。
#!/usr/bin/expect set timeout 20 set user [lindex $argv 0] set password [lindex $argv 1] spawn su $user expect "Password:" send "$password\r"; interact
如下所示執行上面的expect程序。
bala@localhost $ ./su.exp guest guest spawn su guest Password: guest@localhost $
運行上面的腳本後,從bala用戶帳戶登錄到guest用戶帳戶。
6. SSH登錄到另一臺計算機
下面給出的expect程序項目可自動從一臺計算機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
執行上面的expect程序如下所示。
guest@host1 $ ./ssh.exp 192.168.1.2 root password spawn ssh [email protected] Password: Last login: Sat Oct 9 04:11:35 2010 from host1.geetkstuff.com root@host2 #