expect的使用

  • 變量
  • 參數變量
  • if條件語句

  • 變量
    定義:set var value
     eg:set passwd "1234"
    打印expect腳本信息,可用send_user、puts用法類似shell中echo
    [root@xt expects]# cat var.exp
    #!/usr/bin/expect
    set passwd "1234"
    puts $passwd
    send_user "$passwd\n"
    [root@xt expects]# expect var.exp
    1234
    1234
    [root@xt expects]# 
  • 參數變量
    shell腳本中使用$0,$1,$2,$#,$@等表示特殊參數變量,except中使用$argv表示參數數組,使用【lindex $argv n】,n從0開始表接受的第一個參數,$argv0表示腳本名稱如同shell的$0,$argc表示參數 的個數如同shell中$# ,[lrange $argv 0 2] 表示1~3的參數。
    [root@xt expects]# cat canshu.exp 
    #!/usr/bin/expect
    set name [lindex $argv 0]
    set home [lindex $argv 1]
    set age  [lindex $argv 2]
    puts "$name\t$home\t$age"
    puts "$argc"
    send_user "$argv0 [lrange $argv 0 2]\n"
    [root@xt expects]# expect canshu.exp xuetong gx 18
    xuetong gx  18
    3
    canshu.exp xuetong gx 18
    [root@xt expects]# 

    執行腳本時必須要輸入參數,沒提示判斷輸入參數功能。可以通過if語句實現

  • if語句
    if {條件表達式} {
     指令
    } else {
     指令
    }
    如之前的腳本可以添加判斷傳參個數條件:
    if {$argc != 3} {
    send_user "usage:expect $argv0 name home age\n"
    exit
    }
    #!/usr/bin/expect
    if   {$argc < 10}  {
    puts "error idea!"
    }   else   {
    puts "bingo !"
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章