首页 > 学技术 > 技术网文 > 网络安全 > 正文

[保留] 如何在ping 命令结果前面加上时间日期!!!


来源 chinaunix.net 酷勤网整理

我现在打算测试一个网络是否正常.要观察几天.打算用ping的方式检查.

但只有下面的显示:

Pinging 10.111.23.1 with 32 bytes of data:

Reply from 10.111.23.1 : bytes=32 time=2ms TTL=255
Reply from 10.111.23.1 : bytes=32 time=2ms TTL=255
Reply from 10.111.23.1 : bytes=32 time=1ms TTL=255

无法定位是在哪个时间里出现的.我想在前面加上时间如:

Pinging 10.111.23.1 with 32 bytes of data:

[color=red]2005-09-09 00:00:00 [/color]Reply from 10.111.23.1 : bytes=32 time=2ms TTL=255
[color=red]2005-09-09 00:00:01 [/color]Reply from 10.111.23.1 : bytes=32 time=2ms TTL=255
[color=red]2005-09-09 00:00:02 [/color]Reply from 10.111.23.1 : bytes=32 time=1ms TTL=255

哪位大侠知道bat的批处理该如何实现?



 archangle 回复于:2005-09-09 13:31:11

我有一个笨办法
while [ 1 ];do
date;ping ip -c 1
done


 jhgzzq 回复于:2005-09-09 13:55:43

while [ 1 ];do 
date;ping ip -c 1 
done

这个写在bat里是无法执行的吧.能否具体点呢


 jhgzzq 回复于:2005-09-09 16:39:03

怎么没有人回复哟.....


 archangle 回复于:2005-09-09 16:46:59

引用:
while [ 1 ];do
date;ping ip -c 1
done

这个写在bat里是无法执行的吧.能否具体点呢


我以为你是linux系统。
很久没碰dos了。帮不了你。


 AmoyOriole 回复于:2005-09-13 17:45:06

@echo off
:START
date/t >> aa.txt
time/t >> aa.txt
ping 10.111.23.1 -n 10 >>aa.txt
goto START

稍微变通的方法,呵呵。

[ 本帖最后由 AmoyOriole 于 2006-4-4 08:57 编辑 ]


 jhgzzq 回复于:2005-09-13 19:10:04

谢谢:AmoyOriole

不过这种格式打印出来的结果时间怎么一直不变呢?是语句哪里有问题?

2005-09-13 星期二 
19:09

Pinging 134.230.55.1 with 32 bytes of data:

Reply from 134.230.55.1: bytes=32 time=2ms TTL=255
Reply from 134.230.55.1: bytes=32 time=2ms TTL=255
Reply from 134.230.55.1: bytes=32 time=2ms TTL=255

Ping statistics for 134.230.55.1:
    Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 2ms, Maximum = 2ms, Average = 2ms
2005-09-13 星期二 
19:09

Pinging 134.230.55.1 with 32 bytes of data:

Reply from 134.230.55.1: bytes=32 time=2ms TTL=255
Reply from 134.230.55.1: bytes=32 time=3ms TTL=255
Reply from 134.230.55.1: bytes=32 time=2ms TTL=255

Ping statistics for 134.230.55.1:
    Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 2ms, Maximum = 3ms, Average = 2ms
2005-09-13 星期二 
19:09

Pinging 134.230.55.1 with 32 bytes of data:

Reply from 134.230.55.1: bytes=32 time=2ms TTL=255

Ping statistics for 134.230.55.1:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 2ms, Maximum = 2ms, Average = 2ms


 SuperCube 回复于:2005-09-14 10:09:51

time/t只精确到分钟。
改成ehco. |time >;>; aa.txt 就可以了。


 4℃華客 回复于:2005-09-14 10:42:46

谢谢了,我又学到了一些东西!


 slash001 回复于:2005-09-14 12:03:39


Set shell = WScript.CreateObject("WScript.Shell")
Set re=New RegExp
re.Pattern = "^Reply|^Request"
Set myping=shell.Exec("ping 192.168.0.249")
while Not myping.StdOut.AtEndOfStream
strLine = myping.StdOut.ReadLine()
r=re.Test(strLine)
If r Then
WScript.Echo date & " "& time & chr(9) & strLine
End if
Wend


保存成tping.vbs
在command下执行cscript tping.vbs

输出结果
2005-9-14 12:02:01      Reply from 192.168.0.249: bytes=32 time<10ms TTL=64
2005-9-14 12:02:02      Reply from 192.168.0.249: bytes=32 time<10ms TTL=64
2005-9-14 12:02:03      Reply from 192.168.0.249: bytes=32 time<10ms TTL=64
2005-9-14 12:02:04      Reply from 192.168.0.249: bytes=32 time<10ms TTL=64


 joefun 回复于:2005-09-19 07:37:55

slash001 GG的脚本的确8错! :em02:  :em02:


 carrison 回复于:2005-09-19 09:52:39

还是vbs功能强大,呵呵,谁用perl来一个?


 slash001 回复于:2005-09-19 11:25:07

perl的代码

#!/usr/bin/perl
open(PING, "ping 192.168.0.249|");
while (<PING>)
{
if ($_ =~ /^Reply|^Request/)
{
my @date=localtime(time);
printf("%d-%02d-%02d %02d:%02d:%02d %s", $date[5]+1900, $date[4]+1, $date[3], $date[2], $date[1], $date[0], $_);
}
}
close(PING);


[ 本帖最后由 slash001 于 2005-11-15 11:41 编辑 ]


 b.s.d 回复于:2005-09-19 17:50:48

C:\>;cscript tping.vbs
Microsoft (R) Windows 脚本宿主版本 5.1 for Windows
版权所有(C) Microsoft Corporation 1996-1999. All rights reserved.

C:\tping.vbs(4, 1) Microsoft VBScript 运行时错误: 对象不支持此属性或方法: 'shell
.Exec'


 slash001 回复于:2005-09-19 18:20:55

我是在Win2000下测试的
Microsoft (R) Windows Script Host Version 5.6


 carrison 回复于:2005-09-20 08:41:34

引用:原帖由 "slash001"]
 发表:



难不住你了,老弟再用C写一个?哈哈 :em02:


 carrison 回复于:2005-09-20 08:44:13

XP下也没问题
C:\>;cscript pt.vbs
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

2005-9-20 8:43:21       Reply from 10.20.33.3: bytes=32 time=1ms TTL=64
2005-9-20 8:43:22       Reply from 10.20.33.3: bytes=32 time<1ms TTL=64
2005-9-20 8:43:23       Reply from 10.20.33.3: bytes=32 time<1ms TTL=64
2005-9-20 8:43:24       Reply from 10.20.33.3: bytes=32 time<1ms TTL=64

Perl下也不错
C:\>;perl pt2.pl
2005-09-20 09:08:32 Reply from 10.20.33.3: bytes=32 time=1ms TTL=64
2005-09-20 09:08:33 Reply from 10.20.33.3: bytes=32 time<1ms TTL=64
2005-09-20 09:08:34 Reply from 10.20.33.3: bytes=32 time=1ms TTL=64
2005-09-20 09:08:35 Reply from 10.20.33.3: bytes=32 time<1ms TTL=64


 剑心通明 回复于:2005-09-20 09:22:53

收藏,不错不错


 b.s.d 回复于:2005-09-20 09:32:06

[quote="b.s.d"]C:\>;cscript tping.vbs
Microsoft (R) Windows 脚本宿主版本 5.1 for Windows
版权所有(C) Microsoft Corporation 1996-1999. All rights reserved.

C:\tping.vbs(4, 1) Microsoft VBScript 运行时错误: 对?.........

我的是2003


 slash001 回复于:2005-09-20 10:11:11

C不怎么用,随便写了一个,呵呵
Win2000 Cygwin下编译测试通过

#include <stdio.h>;
#include <string.h>;
#include <time.h>;

int main(int argc, char *argv[])
{
time_t clock;
struct tm *tm;
char tbuf[20];

FILE *res;
char buf[256];
res=popen("ping 192.168.0.249", "r");

while (fgets(buf, sizeof(buf), res))
{
if (bcmp(buf, "Reply", 5) == 0 || bcmp(buf, "Request", 7) == 0)
{
time(&clock);
tm=localtime(&clock );
strftime(tbuf, 20, "%Y-%m-%d %H:%M:%S", tm);
printf("%s\t%s", tbuf, buf);
}
}
pclose(res);
return 0;
}



 slash001 回复于:2005-09-20 10:40:14

引用:原帖由 "b.s.d" 发表:

我的是2003


将Windows脚本宿主升级到5.6试试


 carrison 回复于:2005-09-20 12:29:23

引用:原帖由 "slash001"]
 发表:


unix下C编程也会,老弟全才啊, 就差Java的了 :em02: 
你让俺看到了中国软件的希望啊,哈哈


 slash001 回复于:2005-09-20 13:23:08

呵呵,我不是做开发的,就会简单的瞎写点,见笑了


 carrison 回复于:2005-09-20 13:50:44

呵呵,做管理的都会瞎写点就很难得了


 platinum 回复于:2005-09-20 15:25:52

如果是在 Linux 下面,可以这样

# while :;do ping -c 1 172.17.39.251|awk '/ttl=/'|sed "s/^/`date +%Y-%m-%d\|%T` /";sleep 1;done



显示效果如下
引用:
[root@PT_LINUX boot]# while :;do ping -c 1 172.17.39.251|awk '/ttl=/'|sed "s/^/`date +%Y-%m-%d\|%T` /";sleep 1;done
2005-09-20|15:24:40 64 bytes from 172.17.39.251: icmp_seq=0 ttl=128 time=0.240 ms
2005-09-20|15:24:41 64 bytes from 172.17.39.251: icmp_seq=0 ttl=128 time=0.235 ms
2005-09-20|15:24:42 64 bytes from 172.17.39.251: icmp_seq=0 ttl=128 time=0.220 ms
2005-09-20|15:24:43 64 bytes from 172.17.39.251: icmp_seq=0 ttl=128 time=0.224 ms
2005-09-20|15:24:45 64 bytes from 172.17.39.251: icmp_seq=0 ttl=128 time=0.211 ms
2005-09-20|15:24:46 64 bytes from 172.17.39.251: icmp_seq=0 ttl=128 time=0.211 ms
2005-09-20|15:24:47 64 bytes from 172.17.39.251: icmp_seq=0 ttl=128 time=0.222 ms
2005-09-20|15:24:48 64 bytes from 172.17.39.251: icmp_seq=0 ttl=128 time=0.221 ms
2005-09-20|15:24:49 64 bytes from 172.17.39.251: icmp_seq=0 ttl=128 time=0.222 ms

[root@PT_LINUX boot]#




 无心。有心 回复于:2005-09-26 08:48:18

我想请问一下为什么在我的机子上这个命令不行呢 :em14:


 Hex 回复于:2005-09-26 23:27:28

引用:原帖由 "slash001"]
 发表:



cool! :P


 ioiioi 回复于:2005-09-28 22:09:41

哪位高手可以将tping.vbs更改一下,可以自己设定ip和一些参数?
比如cscript tping.vbs 192.168.1.1 -t -l 1000
那就完美了。


 slash001 回复于:2005-09-30 10:01:57


Dim args, flag, unsuccOut
args=""
otherout=""
flag=0

If WScript.Arguments.count = 0 Then
WScript.Echo "Usage: cscript tping.vbs [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]"
WScript.Echo "                         [-s count] [[-j host-list] | [-k host-list]]"
WScript.Echo "                         [-r count] [-w timeout] destination-list"
wscript.quit
End if

For i=0 to WScript.Arguments.count - 1
args=args & " " & WScript.Arguments(i)
Next

Set shell = WScript.CreateObject("WScript.Shell") 
Set re=New RegExp 
re.Pattern="^Reply|^Request" 
Set myping=shell.Exec("ping" & args)

while Not myping.StdOut.AtEndOfStream 
   strLine=myping.StdOut.ReadLine() 
   r=re.Test(strLine) 
   If r Then 
WScript.Echo date & " "& time & chr(9) & strLine
flag=1
   Else
unsuccOut=unsuccOut & strLine
   End if 
Wend

if flag = 0 then
WScript.Echo unsuccOut
end if


E:\>;cscript tping.vbs 192.168.0.249 -t -l 1000
Microsoft (R) Windows Script Host Version 5.6
版权所有(C) Microsoft Corporation 1996-2001。保留所有权利。

2005-9-30 10:03:29      Reply from 192.168.0.249: bytes=1000 time<10ms TTL=64
2005-9-30 10:03:30      Reply from 192.168.0.249: bytes=1000 time<10ms TTL=64
2005-9-30 10:03:31      Reply from 192.168.0.249: bytes=1000 time<10ms TTL=64
2005-9-30 10:03:32      Reply from 192.168.0.249: bytes=1000 time<10ms TTL=64
2005-9-30 10:03:33      Reply from 192.168.0.249: bytes=1000 time<10ms TTL=64
2005-9-30 10:03:34      Reply from 192.168.0.249: bytes=1000 time<10ms TTL=64
2005-9-30 10:03:35      Reply from 192.168.0.249: bytes=1000 time<10ms TTL=64
2005-9-30 10:03:36      Reply from 192.168.0.249: bytes=1000 time<10ms TTL=64


 liutongzhu 回复于:2005-10-08 16:13:50

   
zzzzzz


 可观 回复于:2005-10-09 09:54:23

收藏,不错。


 xuesp001 回复于:2005-10-10 09:51:02

slash001的方法很不错罗!


 mzd73 回复于:2005-10-10 09:55:37

好办法


 plumlee 回复于:2005-10-15 13:51:00

slash001
你在CU才发了不够30帖,帖帖都精华呀~!!!


 asd2004 回复于:2005-10-15 15:13:28

太COOL了, slash001  你就是我的偶像啊!!


 xiaaifei 回复于:2005-10-15 18:25:29

学习ING


 Rcfeng 回复于:2005-10-16 03:36:45

用fping咯,windows版本的
http://www.kwakkelflap.com这里可以下载128K。
加-D参数或者-T参数。完全可以替换windows的ping,速度也更快。
下面这个是python的ping代码,自己改改增加一个这个输出timestamp的参数也可以。

import sys
import os
import struct
import array
import time
import select
import binascii
import math
import getopt
import string
import socket

# total size of data (payload)
ICMP_DATA_STR = 56  

# initial values of header variables
ICMP_TYPE = 8
ICMP_TYPE_IP6 = 128
ICMP_CODE = 0
ICMP_CHECKSUM = 0
ICMP_ID = 0
ICMP_SEQ_NR = 0

# Package definitions.
__program__   = 'ping'
__version__   = '0.5a'
__date__      = '2004/15/12'
__author__    = 'Lars Strand <lars at unik no>;'
__licence__   = 'GPL'
__copyright__ = 'Copyright (C) 2004 Lars Strand'

def _construct(id, size, ipv6):
    """Constructs a ICMP echo packet of variable size
    """

    # size must be big enough to contain time sent
    if size < int(struct.calcsize("d")):
        _error("packetsize to small, must be at least %d" % int(struct.calcsize("d")))
    
    # construct header
    if ipv6:
        header = struct.pack('BbHHh', ICMP_TYPE_IP6, ICMP_CODE, ICMP_CHECKSUM, \
                             ICMP_ID, ICMP_SEQ_NR+id)
    else:
        header = struct.pack('bbHHh', ICMP_TYPE, ICMP_CODE, ICMP_CHECKSUM, \
                             ICMP_ID, ICMP_SEQ_NR+id)

    # if size big enough, embed this payload
    load = "-- IF YOU ARE READING THIS YOU ARE A NERD! --"
    
    # space for time
    size -= struct.calcsize("d")

    # construct payload based on size, may be omitted :)
    rest = ""
    if size >; len(load):
        rest = load
        size -= len(load)

    # pad the rest of payload
    rest += size * "X"

    # pack
    data = struct.pack("d", time.time()) + rest
    packet = header + data          # ping packet without checksum
    checksum = _in_cksum(packet)    # make checksum

    # construct header with correct checksum
    if ipv6:
        header = struct.pack('BbHHh', ICMP_TYPE_IP6, ICMP_CODE, checksum, \
                             ICMP_ID, ICMP_SEQ_NR+id)
    else:
        header = struct.pack('bbHHh', ICMP_TYPE, ICMP_CODE, checksum, ICMP_ID, \
                             ICMP_SEQ_NR+id)

    # ping packet *with* checksum
    packet = header + data 

    # a perfectly formatted ICMP echo packet
    return packet

def _in_cksum(packet):
    """THE RFC792 states: 'The 16 bit one's complement of
    the one's complement sum of all 16 bit words in the header.'

    Generates a checksum of a (ICMP) packet. Based on in_chksum found
    in ping.c on FreeBSD.
    """

    # add byte if not dividable by 2
    if len(packet) & 1:              
        packet = packet + '\0'

    # split into 16-bit word and insert into a binary array
    words = array.array('h', packet) 
    sum = 0

    # perform ones complement arithmetic on 16-bit words
    for word in words:
        sum += (word & 0xffff) 

    hi = sum >;>; 16 
    lo = sum & 0xffff 
    sum = hi + lo
    sum = sum + (sum >;>; 16)
    
    return (~sum) & 0xffff # return ones complement

def pingNode(alive=0, timeout=1.0, ipv6=0, number=sys.maxint, node=None, \
             flood=0, size=ICMP_DATA_STR):
    """Pings a node based on input given to the function.
    """

    # if no node, exit
    if not node:
        _error("")

    # if not a valid host, exit
    if ipv6:
        if socket.has_ipv6:
            try:
                info, port = socket.getaddrinfo(node, None)
                host = info[4][0]
                # do not print ipv6 twice if ipv6 address given as node
                if host == node: 
                    noPrintIPv6adr = 1
            except:
                _error("cannot resolve %s: Unknow host" % node)
        else:
            _error("No support for IPv6 on this plattform")
    else:    # IPv4
        try:
            host = socket.gethostbyname(node)
        except:
            _error("cannot resolve %s: Unknow host" % node)

    # trying to ping a network?
    if not ipv6:
        if int(string.split(host, ".")[-1]) == 0:
            _error("no support for network ping")

    # do some sanity check
    if number == 0:
        _error("invalid count of packets to transmit: '%s'" % str(a))
    if alive:
        number = 1

    # Send the ping(s)
    start = 1; mint = 999; maxt = 0.0; avg = 0.0
    lost = 0; tsum = 0.0; tsumsq = 0.0

    # tell the user what we do
    if not alive:
        if ipv6:
            # do not print the ipv6 twice if ip adress given as node
            # (it can be to long in term window)
            if noPrintIPv6adr == 1:
                # add 40 (header) + 8 (icmp header) + payload
                print "PING %s : %d data bytes (40+8+%d)" % (str(node), \
                                                             40+8+size, size)
            else:
                # add 40 (header) + 8 (icmp header) + payload
                print "PING %s (%s): %d data bytes (40+8+%d)" % (str(node), \
                                                                 str(host), 40+8+size, size)
        else:
            # add 20 (header) + 8 (icmp header) + payload
            print "PING %s (%s): %d data bytes (20+8+%d)" % (str(node), str(host), \
                                                             20+8+size, size)
        
    # trap ctrl-d and ctrl-c
    try:
        
        # send the number of ping packets as given
        while start <= number:
            lost += 1 # in case user hit ctrl-c
            
            # create the IPv6/IPv4 socket
            if ipv6:
                # can not create a raw socket if not root or setuid to root
                try:
                    pingSocket = socket.socket(socket.AF_INET6, socket.SOCK_RAW, \
                                               socket.getprotobyname("ipv6-icmp"))
                except socket.error, e:
                    print "socket error: %s" % e
                    _error("You must be root (uses raw sockets)" % os.path.basename(sys.argv[0]))
                    
            # IPv4
            else:
                # can not create a raw socket if not root or setuid to root
                try:
                    pingSocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, \
                                               socket.getprotobyname("icmp"))
                except socket.error, e:
                    print "socket error: %s" % e
                    _error("You must be root (%s uses raw sockets)" % os.path.basename(sys.argv[0]))
                
            packet = _construct(start, size, ipv6) # make a ping packet

            # send the ping
            try:
                pingSocket.sendto(packet,(node,1))
            except socket.error, e:
                _error("socket error: %s" % e)

            # reset values
            pong = ""; iwtd = []

            # wait until there is data in the socket
            while 1:
                # input, output, exceptional conditions
                iwtd, owtd, ewtd = select.select([pingSocket], [], [], timeout)
                break # no data and timout occurred 

            # data on socket - this means we have an answer
            if iwtd:  # ok, data on socket
                endtime = time.time()  # time packet received
                # read data (we only need the header)
                pong, address = pingSocket.recvfrom(size+48)
                lost -= 1 # in case user hit ctrl-c

                # examine packet
                # fetch TTL from IP header
                if ipv6:
                    # since IPv6 header and any extension header are never passed
                    # to a raw socket, we can *not* get hoplimit field..
                    # I hoped that a socket option would help, but it's not
                    # supported:
                    #   pingSocket.setsockopt(IPPROTO_IPV6, IPV6_RECVHOPLIMIT, 1)
                    # so we can't fetch hoplimit..

                    # fetch hoplimit
                    #rawPongHop = struct.unpack("c", pong[7])[0]

                    # fetch pong header
                    pongHeader = pong[0:8]
                    pongType, pongCode, pongChksum, pongID, pongSeqnr = \
                              struct.unpack("bbHHh", pongHeader)

                    # fetch starttime from pong
                    starttime = struct.unpack("d", pong[8:16])[0]

                # IPv4
                else:
                    # time to live
                    rawPongHop = struct.unpack("s", pong[8])[0]

                    # convert TTL from 8 bit to 16 bit integer
                    pongHop = int(binascii.hexlify(str(rawPongHop)), 16)

                    # fetch pong header
                    pongHeader = pong[20:28]
                    pongType, pongCode, pongChksum, pongID, pongSeqnr = \
                              struct.unpack("bbHHh", pongHeader)

                    # fetch starttime from pong
                    starttime = struct.unpack("d", pong[28:36])[0]

                # valid ping packet received?
                if not pongSeqnr == start:
                    pong = None

            # NO data on socket - timeout waiting for answer
            if not pong:
                if alive:
                    print "no reply from %s (%s)" % (str(node), str(host))
                else:
                    print "ping timeout: %s (icmp_seq=%d) " % (host, start)

                # do not wait if just sending one packet
                if number != 1 and start < number:
                    time.sleep(flood ^ 1)
                start += 1
                continue  # lost a packet - try again

            triptime  = endtime - starttime # compute RRT
            tsum     += triptime            # triptime for all packets (stddev)
            tsumsq   += triptime * triptime # triptime^2  for all packets (stddev)

            # compute statistic
            maxt = max ((triptime, maxt))
            mint = min ((triptime, mint))

            if alive:
                print str(node) + " (" + str(host) +") is alive"
            else:
                if ipv6:
                    # size + 8 = payload + header
                    print "%d bytes from %s: icmp_seq=%d time=%.5f ms" % \
                          (size+8, host, pongSeqnr, triptime*1000)
                else:
                    print "%d bytes from %s: icmp_seq=%d ttl=%s time=%.5f ms" % \
                          (size+8, host, pongSeqnr, pongHop, triptime*1000)

            # do not wait if just sending one packet
            if number != 1 and start < number:
                # if flood = 1; do not sleep - just ping                
                time.sleep(flood ^ 1) # wait before send new packet

            # the last thing to do is update the counter - else the value
            # (can) get wrong when computing summary at the end (if user
            # hit ctrl-c when pinging)
            start += 1
            # end ping send/recv while

    # if user ctrl-d or ctrl-c
    except (EOFError, KeyboardInterrupt):
        # if user disrupts ping, it is most likly done before
        # the counter get updates - if do not update it here, the
        # summary get all wrong.
        start += 1
        pass

    # compute and print som stats
    # stddev computation based on ping.c from FreeBSD
    if start != 0 or lost >; 0:  # do not print stats if 0 packet sent
        start -= 1              # since while is '<='
        avg = tsum / start      # avg round trip
        vari = tsumsq / start - avg * avg 
        # %-packet lost
        if start == lost:
            plost = 100
        else:
            plost = (lost/start)*100

        if not alive:
            print "\n--- %s ping statistics ---" % node
            print "%d packets transmitted, %d packets received, %d%% packet loss" % \
                  (start, start-lost, plost)
            # don't display summary if 100% packet-loss
            if plost != 100:
                print "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms" % \
                      (mint*1000, (tsum/start)*1000, maxt*1000, math.sqrt(vari)*1000)

    pingSocket.close()
    
def _error(err):
    """Exit if running standalone, else raise an exception
    """

    if __name__ == '__main__':
        print "%s: %s" % (os.path.basename(sys.argv[0]), str(err))
        print "Try `%s --help' for more information." % os.path.basename(sys.argv[0])
        sys.exit(1)
    else:
        raise Exception, str(err)
    
def _usage():
    """Print usage if run as a standalone program
    """
    print """usage: %s [OPTIONS] HOST
Send ICMP ECHO_REQUEST packets to network hosts.

Mandatory arguments to long options are mandatory for short options too.
  -c, --count=N    Stop after sending (and receiving) 'N' ECHO_RESPONSE
                   packets.
  -s, --size=S     Specify the number of data bytes to be sent. The default
                   is 56, which translates into 64 ICMP data bytes when
                   combined with the 8 bytes of ICMP header data.
  -f, --flood      Flood ping. Outputs packets as fast as they come back. Use
                   with caution!
  -6, --ipv6       Ping using IPv6.
  -t, --timeout=s  Specify a timeout, in seconds, before a ping packet is
                   considered 'lost'.
  -h, --help       Display this help and exit

Report bugs to lars [at] gnist org""" % os.path.basename(sys.argv[0])


if __name__ == '__main__':
    """Main loop
    """

    # version control
    version = string.split(string.split(sys.version)[0][:3], ".")
    if map(int, version) < [2, 3]:
        _error("You need Python ver 2.3 or higher to run!")

    try:
        # opts = arguments recognized,
        # args = arguments NOT recognized (leftovers)
        opts, args = getopt.getopt(sys.argv[1:-1], "hat:6c:fs:", \
                                   ["help", "alive", "timeout=", "ipv6", \
                                    "count=", "flood", "packetsize="])
    except getopt.GetoptError:
        # print help information and exit:
        _error("illegal option(s) -- " + str(sys.argv[1:]))

    # test whether any host given
    if len(sys.argv) >;= 2:
        node = sys.argv[-1:][0]   # host to be pinged
        if node[0] == '-' or node == '-h' or node == '--help' :  
            _usage()
    else:
        _error("No arguments given")

    if args:
        _error("illegal option -- %s" % str(args))
        
    # default variables
    alive = 0; timeout = 1.0; ipv6 = 0; count = sys.maxint;
    flood = 0; size = ICMP_DATA_STR

    # run through arguments and set variables
    for o, a in opts:
        if o == "-h" or o == "--help":    # display help and exit
            _usage()
            sys.exit(0)
        if o == "-t" or o == "--timeout": # timeout before "lost"
            try:
                timeout = float(a)
            except:
                _error("invalid timout: '%s'" % str(a))
        if o == "-6" or o == "--ipv6":    # ping ipv6
            ipv6 = 1
        if o == "-c" or o == "--count":   # how many pings?
            try:
                count = int(a)
            except:
                _error("invalid count of packets to transmit: '%s'" % str(a))
        if o == "-f" or o == "--flood":   # no delay between ping send
            flood = 1
        if o == "-s" or o == "--packetsize":  # set the ping payload size
            try:
                size = int(a)
            except:
                _error("invalid packet size: '%s'" % str(a))
        # just send one packet and say "it's alive"
        if o == "-a" or o == "--alive":   
            alive = 1

    # here we send
    pingNode(alive=alive, timeout=timeout, ipv6=ipv6, number=count, \
             node=node, flood=flood, size=size)
    # if we made it this far, do a clean exit
    sys.exit(0)

### end



 plumlee 回复于:2005-10-20 16:56:42

今天试了。可以引入到excel中做成曲线图~~


 excellent 回复于:2005-11-03 16:30:30

引用:原帖由 AmoyOriole 于 2005-9-13 17:45 发表
@echo off
:START
date/t >;>; aa.txt
time/t >;>; aa.txt
ping 10.111.23.1 -n 10 >;>;aa.txt
goto START

稍微变通的方法,呵呵。 




问一下 ">;>; " 是什么意思呢??


 rainballdh 回复于:2005-11-04 19:31:09

引用:原帖由 archangle 于 2005-9-9 13:31 发表
我有一个笨办法
while [ 1 ];do
date;ping ip -c 1
done 


这个怎么运行呀?


 rainballdh 回复于:2005-11-04 19:32:18

知道料,直接在终端运行


 xyco 回复于:2005-11-05 09:23:15

强啊!收起


 zhxf_1 回复于:2005-11-09 15:13:56

楼上的,语法好象有点问题啊 !


 webcup 回复于:2005-11-09 20:50:19

CreateObject&#40

Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

C:ping.vbs(1, 34) Microsoft VBScript compilation error: Syntax error


 sun-bone 回复于:2006-03-20 18:44:16

在cmd下使用ping的命令长ping一个地址时,中途可以使用“Ctrl”+“Break”组合键中断一下ping,只是显示从开始ping到你发指令这一时间段的ping的情况,能不能把这个组合键的功能也加进去


 lzl0310lzl 回复于:2006-03-23 16:18:35

:-L:victory::time::time::kiss::handshake:handshake:handshake:handshake


 馒头血案 回复于:2006-03-25 02:35:30

呵呵。


 inhell 回复于:2006-03-27 11:04:48

强帖留名


 ainimeiban 回复于:2006-03-28 22:41:12

XP下如何运行那个..




原文链接:http://bbs.chinaunix.net/viewthread.php?tid=608813
转载请注明作者名及原文出处



收藏本页到: