Opensolaris: expect用法小結

expect是基於tcl演變而來的,很多語法和tcl類似,基本的語法見如下示例:

#!/usr/tcl/bin/expect -f

#page_autofiler_cifs_mount.exp mount_name remote_host remote_name user_name password

set mount_name [lindex $argv 0]
set remote_host [lindex $argv 1]
set remote_name [lindex $argv 2]
set user_name [lindex $argv 3]
set password [lindex $argv 4]

spawn sh /usr/local/istor/cli/scripts/page_autofiler_cifs_mount.sh $mount_name $remote_host $remote_name $user_name
#eval exp_spawn sh /usr/local/istor/cli/scripts/page_autofiler_cifs_mount.sh $mount_name $remote_host $remote_name $user_name

expect {
      "assword:" {
            send "$password\r"
            expect {
                   "assword:" {
                           exit 1
                   }
                   EOF {
                   }
           }
     }
    eof{
     }
}

set ret [exp_wait]

exit [lindex $ret 3]

 

1.首行加/usr/tcl/bin/expect

2.spawn後加上需要執行的shell命令

3.只有spawn執行的結果纔會被expect捕獲到

4.send將spawn需要的信息發送給spawn啓動的進程.

5.針對cifs mount,第一次需要輸入密碼,第二次由於系統已記憶上次輸入的密碼,則不會提示用戶去輸入,所以我們要用分支的情況去處理,否則會報send: spawn id exp6 not open錯誤.

6.如果密碼錯誤,系統後臺會顯示再次輸入密碼,這時可以再次捕獲然後退出.

7.spawn命令出現的交互如果expect匹配不上的話,程序會按timeout設置進行等待,如果第二次運行本例的情況,相當於spawn直接發出eof,程序會直接執行expect eof.

8.expect eof是必須的,否則可能導致執行結果不正確.如下

spawn passwd $user
expect "New Password:"
send "$passwd\r"
expect "Re-enter new Password:"
send "$passwd\r"
expect EOF

最後expect EOF是必須的,否則程序在真正執行完成前就已經退出.

9.exp_wait等待shell運行結束.

10.執行結果有4個字段,最後一個代表shell返回值.

set pid [lindex $ret 0]

set spawn_id [lindex $ret 1]

set os_error [lindex $ret 2]

set exit_status [lindex $ret 3]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章