今天學shell腳本的時候,看到了expect,本來想隨便了解一下好了,以后有用了再看,但是后來想了想還是好好看看吧,嘿嘿,然后百度呀啥的,有一篇文章推薦了http://www.thegeekstuff.com/2010/10/expect-examples/ 英文的,以前很有心理壓力,一看到英文的,今天不知咋地,想看看,一看,發現只有自己認真的看,再加上Google翻譯,還是可以看懂的。就把自己學的看的總結一下,寫博客的時候,有時要選原創啊,轉載啊,其實很多時候分不清原創的具體定義是啥,看着文檔,看着書,然后自己做的總結不知是不是?
1:有三個命令
send – to send the strings to the process
expect – wait for the specific string from the process
spawn – to start the command
2:hello world初試,vim expect1.exp
#/usr/bin/expect #filename expect1.sh #expect實驗 交互式輸入輸出,執行腳本后,當你輸入hello的時候,它會自動輸出world expect "hello" send "world"
這個地方糾結了好久,因為一直用的是expect.sh ,然后執行的時候也是sh expect.sh,后來仔細看文檔才發現 Generally, expect script files has .exp as extensions 這一句。執行的時候也是 expect expect1.exp
執行的時候,若輸入的不是他期望的值,他會一直讓你輸
我的理解: 如果輸入的值和expect期望的值一樣,就send返回一個設定的值
3:設置輸入時,超時的時間
#/usr/bin/expect #filename expect2.exp #交互輸入輸出的時候,如果你超過多少時間,那么將直接輸出返回的值 set timeout 10 expect "hello" send "world\n"
當執行腳本后,若10s沒有輸入任何東西,那么將直接輸出send值。
4:Automate User Processes With Expect 和進程進行交互?(解釋不出那種感覺)
addtion腳本:
#!/bin/bash #filename addtion.sh read -p "Enter the number1:" no; read -p "Enter the number2:" no2; let result=$no+$no2 echo "result:$result"
expect.exp腳本:
#!/usr/bin/expect #filename addition.exp #和addtion.sh進行交互 set timeout 20 spawn sh addtion.sh expect "Enter the number1:" { send "12\r" } expect "Enter the number2:" { send "23\r" } interact
spawn:用來啟動一個新的進程,和addtion.sh進行交互,spawn后的expect和send都是在新的啟動的進程addtion.sh進行交互的。
當addtion.sh有輸出Enter the number1:的時候,就send12,
當addtion.sh有輸出Enter the number2:的時候,就send23
5:練習,比如ssh 上jenkins@f1.y的時,不用輸密碼,自己自動連接上
#!/usr/bin/expect #filename:ssh.exp #ssh的時候自動輸入密碼連接上 spawn ssh jenkins@f1.y expect "password:" { send "jenkins.123\r" } interact
當ssh jenkins@f1.y的時候,會有一個輸出信息,要輸入密碼,在當匹配到password的時候,send密碼進去,就自動連接上了
interact:連接上后,用戶還可以自己進行操作,如果沒有的話,就直接退回到原來的狀態了。也就是執行完里面的操作,又回到原始狀態
6:
match.exp
#!/usr/bin/expect #filename:match.exp #$expect_out(buffer)與$expect_out(0,string) set timeout 20 spawn sh he.sh expect "hello" puts stderr "no match: \ $expect_out(buffer) \n" puts stdout "match : \ $expect_out(0,string) \n" interact
he.sh
#!/bin/bash echo "Sh program"; echo "hello world";
$expect_out(buffer) :匹配之前的存放的位置
$expect_out(0,string) :匹配的存放的地方
例子:
#!/usr/bin/expect set ip "10.0.0.142" set user "root" set password "123456" spawn ssh $user@$ip expect { "yes/no" { send "yes\n";exp_continue } "password:" { send "$password\r" } } interact