Tcl脚本突破了foreach循环

时间:2015-03-11 17:21:53

标签: foreach nested tcl expect

我有一个tcl脚本来登录设备并打印SUCCESS。这是脚本:

文件:(第一个IP有效,可以登录,接下来的3个是假的)。

192.38.133.145
178.18.34.48
183.24.56.3
145.234.67.145

剧本:

#!/bin/expect
package require Expect

set file [open "hosts" r]
set f_data [read $file]
set data [split $f_data "\n"]

foreach host $data {
set timeout 8
    if {$host > 0} {
                ## GETS THE HOST IP##
                set host_ip $host

                ##LOGS INTO THE DEVICE##
                spawn ssh test@$host_ip
                expect {
                        "password:" {
                                puts "SUCCESS"
                        } timeout {
                                puts "Could not connect to host: ${host_ip}"
                                #break
                        }

                }
        send "password\r"
        expect ">"
        send "en\r"
        }
}

如果我没有包含中断,我收到的消息无法连接到主机,但它不是循环到下一个主机,而是发送"en\r"。 当我包含break时,它会给出无法到达主机的消息(第二个IP,这是预期的)并且脚本在那里结束(它不处理第三个IP)。我怎么似乎无法处理第3和第4 IP。 我使用了potrzebie建议的方法:TCL: loops How to get out of inner most loop to outside? 仍然无法让它工作

1 个答案:

答案 0 :(得分:1)

break应该有效。 expect手册页在expect命令的文档中有这个说法:

  

breakcontinue等操作会导致控件结构(即forproc)以通常的方式运行。

我写这样的循环:

foreach host $data {
    # very basic data validation: an ipv4 address contains some dots
    if {[string match {*.*.*.*} $host]} {
        spawn ssh test@$host
        expect {
            "password:" {
                puts "SUCCESS"
                send "password\r"
                exp_continue
            } 
            timeout {
                puts "Could not connect to host: $host"
                continue
            }
            ">" {
                # I see a prompt. Fall out of this "expect loop"
            }
        }
        send "en\r"
        expect ">"

        # do something to close the connection
        send "exit\r"
        expect eof
    }
}