Tcl 脚本跳出 foreach 循环
Tcl script breaks out of foreach loop
我有一个 tcl 脚本来登录设备并打印成功。这是脚本:
文件:(第一个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?
仍然无法正常工作
break
应该可以。 expect
手册页在 expect
命令的文档中这样说:
Actions such as break
and continue
cause control structures (i.e., for
, proc
) to behave in the usual way.
我会这样写你的循环:
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
}
}
我有一个 tcl 脚本来登录设备并打印成功。这是脚本:
文件:(第一个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?
仍然无法正常工作
break
应该可以。 expect
手册页在 expect
命令的文档中这样说:
Actions such as
break
andcontinue
cause control structures (i.e.,for
,proc
) to behave in the usual way.
我会这样写你的循环:
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
}
}