expect實例

Expect的做者Don Libes1990年開始編寫Expect時對Expect作有以下定義:mysql

   (Expect is a software suite for automating interactive toolssql

    Expect的官方主頁對它做了以下介紹:shell

    Expect is a tool for automating interactive applications such as telnet,數據庫

    ftp, passwd, fsck, rlogin, tip, etc. Expect really makes this stuffapp

    trivial. Expect is also useful for testing these same applications. Andide

    by adding Tk, you can also wrap interactive applications in X11 GUIs.函數

    Expect是基於TCL的,做爲一個腳本語言,expect能在無需管理員參與的狀況下實現測試

自動交互(好比passwdfscktelnet),expect也能用於自動測試一些應用程序。ui

    expect的語法和shell的語法很是類似,它支持函數調用,有while語句,switchthis

語句。

1)    expect使用spawn調用其餘的執行程序,好比

    spawn  telnet  218.199.20.98  2600

    可是在使用的過程當中發現spawn不支持管道和重定向,也就是說對於

        ls |more mysql -p < update.sql 這樣的命令spawn不能正確解析。

    解決的辦法是把這些命令放到一個shell腳本里面,在用spawn執行這個shell

    腳本。

 

2)    expect 建立子函數使用proc標誌,也即:

    proc  functionname { parameter1,parameter2 } {

       ......

    }

    調用子函數很是簡單

    functionname  $param1 $param2

3)  expect  使用expect send 組合實現自動交互 ,語法以下:

    expect {

            "login;"  {  send  "$user\n"   }

            "passwd:" {  send  "$passwd\n" }

    }

    使用send的使用後面的內容不顯示給用戶,如要顯示給用戶,應使用send_user

4) 注意點:

   1. expect裏面基本是都是使用{} 而不是使用(),好比函數參數輸入外面應用{},

應該是while { } 而不是 while ( ).

   2. { 應和其餘符合有空格, expect { 正確,expect{ 就會報錯.

   3.  spawn 不支持管道和重定向.

5) 下面是實現的mysql數據庫自動更新的expect腳本:

   proc do_console_login {pass} {

        set timeout 5

    set done 1

    while { $done } {

                expect {

                          "password:" {

                               send "$pass\n"

                          }

                          eof {

                                set done 0

                          }

                }

    }

   }

 

   if {$argc<1} {

        puts stderr "Usage: $argv0  password.\n "

        exit 1

   }

   set PASS    [lindex $argv 0]

   spawn   /usr/local/mysql/data/updatemysql

   do_console_login  $PASS

相關文章
相關標籤/搜索