期望脚本在循环中运行命令

时间:2014-04-29 21:21:25

标签: tcl expect

我很期待。我正在尝试循环运行命令。

  1. ssh into a machine
  2. 多次执行相同的命令
  3. package require Expect
    
    set uname admin
    set password default
    set hostname "182.35.44.35"
    
    #SSH into Appliance
    set timeout 10
    cd /cygwin/bin 
    puts "changed into directory and exec telnet"
    spawn telnet "$hostname"
    
    expect "br"
    exp_send "admin\r"
    expect "Password" 
    exp_send "******\r"
    expect "br"
    exp_send "zzdebugshell\r"
    after 1000
    send "*******\r"
    after 1000
    send "*******\r"
    expect "debugshell#"
    after 1000
    
    set times 0;
    while { $times < 10 } 
    {
    send "vmstat -n 2 5\r"
    set times [expr $times+1];
    }
    
    expect "debugshell"
    exp_send "exit\r"
    
    expect "br"
    exp_send "exit\r"
    exit
    

    Error : debugshell# child process exited abnormally

    你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

这部分看起来不对:

set times 0;
while { $times < 10 } 
{
send "vmstat -n 2 5\r"
set times [expr $times+1];
}

您应该在expect之后执行send,以便在再次绕过循环之前等待提示。你的循环也是非惯用的,并且将大括号放在换行符上根本不适用于Tcl(因为新行是命令终止符,除非引用)。

更正/改进版本将是:

for {set times 0} {$times < 10} {incr times} {
    send "vmstat -n 2 5\r"
    expect "debugshell"
}

你也可以在循环后立即放弃等待提示,因为它现在在循环中。当然。

您还应该(可能)在close之前加wait和{明确} exit

exp_send "exit\r"
# Maybe 'expect' something here...
close
wait
exit

(那些expect "br"行对我来说很奇怪,但也许他们没问题;我不知道你的提示毕竟是什么样的......)