1

我有一个调用 ping 命令并返回其响应的 tcl 代码,代码如下

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 failed”。我匹配“0% 损失”

多谢。

4

3 回答 3

3

您需要捕获对 ping 的 exec 调用,以防它返回错误。这是修改为使用 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
%
于 2012-09-21T09:10:21.843 回答
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
于 2012-09-21T16:51:35.767 回答
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
}
于 2013-02-05T21:53:40.807 回答