2016-02-05 127 views
1

我有一個願望腳本,它會產生,期望併發送並獲取所需的數據。 當我以ex.tcl的形式運行腳本時,它不起作用。Tcl/Tk:在期望腳本中嵌入期望發送腳本

請在下面的代碼中找到更多信息。

#!/usr/bin/wish 

package require Expect 

proc openSession { targetHost } { 
    log_user 1 

    set user $::env(USER) 
    set password "tmp1234" 
    set timeout 60 
    set spawn_id "" 

    puts "Ssh to [email protected]$targetHost" 
    spawn ssh -o UserKnownHostsFile=/dev/null [email protected]$targetHost 
    match_max -i $spawn_id 99999 
    expect { 
     "\(yes\/no\)\? " { send "yes\r" ; exp_continue } 
     "password\:" { puts 2 ; send "$password\r" ; exp_continue } 
     "$ " { puts 3 ; send "\r" ; puts "Ssh Session ready" } 
     timeout { puts 4 ; set spawn_id "" ; puts "Timeout during ssh $targetHost" } 
    } 
    set timeout 10 
    return $spawn_id 
} 

proc closeSession { sshSess args } { 
    puts "Closing Ssh session..." 
    expect -i $sshSess "$ " { send -i $sshSess "exit\r" } 
    expect -i $sshSess "closed." { puts "Connection Closed" } 
    catch { exp_close -i $sshSess } 
    catch { exp_wait -i $sshSess } 
    return 
} 


set sessId [openSession testbng76] 
grid [ttk::button .mybutton -text Mytext] 
closeSession $sessId 

錯誤看出:

Are you sure you want to continue connecting (yes/no)? Error in startup script: wrong # args: should be "send ?options? interpName arg ?arg ...?" 
    while executing 
"send "yes\r" " 
    invoked from within 
"expect { 
     "\(yes\/no\)\? " { send "yes\r" ; exp_continue } 
     "password\:" { puts 2 ; send "$password\r" ; exp_continue } 
     "$ " { p..." 
    (procedure "openSession" line 12) 
    invoked from within 
"openSession testbng76" 
    invoked from within 
"set sessId [openSession testbng76]" 
    (file "./log.tcl" line 36) 

我怎樣才能創造遠程會話,並使用TK獲得所需的輸出?

+0

幹得不錯,掛在spawn_id。您也可以在openSession和closeSession procs中將該變量聲明爲全局變量。 –

回答

4

Tk 有一個send命令與其他啓用Tk的解釋器交談(它的工作方式與Expect完全不同),兩者互相作用。或者更確切地說,當它看到Tk時,期望會退後,並且不會創建send命令。

幸運的是,您可以使用exp_send來代替;它是您想要的功能的另一個名稱,並且Expect始終創建它。例如:

"\(yes\/no\)\? " { exp_send "yes\r" ; exp_continue } 
+2

這樣做是因爲Expect和Tk都早於Tcl的命名空間支持。 –