我有一个tcl代码,它调用ping命令并返回其响应,代码如下
proc ping-igp {} {
foreach i {
127.0.0.1
200.200.200.1
} {
if { [regexp "0% loss" [eval exec "ping $i -n 1" ]]} { puts “$i”} else { puts “$i failed” }
}
}
但在执行时我得到如下的o / p,
% proc ping-igp {} {
foreach i {
127.0.0.1
200.200.200.1
} {
if { [regexp "0% loss" [eval exec "ping $i -n 1" ]]} { puts "$i"} else { puts "
$i failed" }
}
}
% ping-igp
"127.0.0.1"
Pinging 200.200.200.1 with 32 bytes of data:
Request timed out.
Ping statistics for 200.200.200.1:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
child process exited abnormally
%
我想知道当我无法ping 200.200.200.1为什么我的代码不处理else子句并且最终给o / p“200.200.200.1失败”。我匹配“0%损失”
很多Thanx。
答案 0 :(得分:3)
你需要catch exec调用ping,以防它返回错误。这是您的代码修改为使用catch。
proc ping-igp {} {
foreach i {
127.0.0.1
200.200.200.1
} {
if {[catch {exec ping $i -n 1} result]} { set result 0 }
if { [regexp "0% loss" $result]} { puts "$i"} else { puts "$i failed" }
}
}
现在运行它:
% ping-igp
127.0.0.1
200.200.200.1 failed
%
答案 1 :(得分:1)
这是我为自己创建的东西:Tcl的ping proc。它并不完美,但有效:
package require Tclx; # Needed for lassign and wait
# Pings a host and returns 0 if OK, non-zero otherwise
proc ping {host} {
# TODO: Use different command for Windows OS
set childPid [exec ping -c 1 $host > /dev/null 2>@1 &]
lassign [wait $childPid] pid howItEnded exitCode
return $exitCode
}
# Test the ping proc
set hostList {google.com 10.0.0.99 foo.bar}
foreach host $hostList {
set code [ping $host]
puts [format "%4d %s" $code $host]
}
示例输出:
$ tclsh ping_test.tcl
0 google.com
2 10.0.0.99
68 foo.bar
答案 2 :(得分:0)
proc ping_device { router ip_address max_tries } {
set tries 0
while {$tries <= $max_tries} {
if {[catch {exec ping $ip_address -c 5} result]} {
puts "Ping command failed on Linux machine"
incr tries
if {$tries > $max_tries} {
ats_log -error "Giving up on ping"
return 0
}
continue
}
if {[regexp {([1-5]+) *[packets]? *received} $result - packets]} {
puts "Able to ping device: $router and\
successfully received $packets packets"
return 1
} else {
puts "Not Able to ping device: $router"
incr tries
}
}
puts "Giving up on ping, returning 0"
return 0
}