免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2298 | 回复: 2
打印 上一主题 下一主题

[网络管理] 求一个linux ping脚本 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-02-04 10:37 |只看该作者 |倒序浏览
我需要一个linux的ping脚本,记录ping过程中没有ping通的包,输出到指定文件,ping通时不记录,同时记录ping的时间点,先谢谢各位了

论坛徽章:
18
卯兔
日期:2013-09-27 17:41:0615-16赛季CBA联赛之佛山
日期:2016-07-09 17:34:45操作系统版块每周发帖之星
日期:2015-12-02 15:01:04IT运维版块每日发帖之星
日期:2015-12-02 06:20:00IT运维版块每日发帖之星
日期:2015-10-07 06:20:00IT运维版块每日发帖之星
日期:2015-10-03 06:20:00IT运维版块每日发帖之星
日期:2015-10-01 06:20:00羊年新春福章
日期:2015-04-01 17:56:06拜羊年徽章
日期:2015-04-01 17:56:062015年迎新春徽章
日期:2015-03-04 09:49:452015年辞旧岁徽章
日期:2015-03-03 16:54:15天秤座
日期:2015-01-14 06:39:28
2 [报告]
发表于 2014-02-05 21:48 |只看该作者
路过,学习..........

论坛徽章:
0
3 [报告]
发表于 2014-02-06 05:20 |只看该作者
有个ping.py脚本,我是直接拿来改再利用的:ping.py
  1. #!/usr/bin/env python

  2. """
  3.     A pure python ping implementation using raw socket.


  4.     Note that ICMP messages can only be sent from processes running as root.


  5.     Derived from ping.c distributed in Linux's netkit. That code is
  6.     copyright (c) 1989 by The Regents of the University of California.
  7.     That code is in turn derived from code written by Mike Muuss of the
  8.     US Army Ballistic Research Laboratory in December, 1983 and
  9.     placed in the public domain. They have my thanks.

  10.     Bugs are naturally mine. I'd be glad to hear about them. There are
  11.     certainly word - size dependenceies here.

  12.     Copyright (c) Matthew Dixon Cowles, <http://www.visi.com/~mdc/>.
  13.     Distributable under the terms of the GNU General Public License
  14.     version 2. Provided with no warranties of any sort.

  15.     Original Version from Matthew Dixon Cowles:
  16.       -> ftp://ftp.visi.com/users/mdc/ping.py

  17.     Rewrite by Jens Diemer:
  18.       -> http://www.python-forum.de/post-69122.html#69122

  19.     Rewrite by George Notaras:
  20.       -> http://www.g-loaded.eu/2009/10/30/python-ping/

  21.     Revision history
  22.     ~~~~~~~~~~~~~~~~

  23.     November 8, 2009
  24.     ----------------
  25.     Improved compatibility with GNU/Linux systems.

  26.     Fixes by:
  27.      * George Notaras -- http://www.g-loaded.eu
  28.     Reported by:
  29.      * Chris Hallman -- http://cdhallman.blogspot.com

  30.     Changes in this release:
  31.      - Re-use time.time() instead of time.clock(). The 2007 implementation
  32.        worked only under Microsoft Windows. Failed on GNU/Linux.
  33.        time.clock() behaves differently under the two OSes[1].

  34.     [1] http://docs.python.org/library/time.html#time.clock

  35.     May 30, 2007
  36.     ------------
  37.     little rewrite by Jens Diemer:
  38.      -  change socket asterisk import to a normal import
  39.      -  replace time.time() with time.clock()
  40.      -  delete "return None" (or change to "return" only)
  41.      -  in checksum() rename "str" to "source_string"

  42.     November 22, 1997
  43.     -----------------
  44.     Initial hack. Doesn't do much, but rather than try to guess
  45.     what features I (or others) will want in the future, I've only
  46.     put in what I need now.

  47.     December 16, 1997
  48.     -----------------
  49.     For some reason, the checksum bytes are in the wrong order when
  50.     this is run under Solaris 2.X for SPARC but it works right under
  51.     Linux x86. Since I don't know just what's wrong, I'll swap the
  52.     bytes always and then do an htons().

  53.     December 4, 2000
  54.     ----------------
  55.     Changed the struct.pack() calls to pack the checksum and ID as
  56.     unsigned. My thanks to Jerome Poincheval for the fix.


  57.     Last commit info:
  58.     ~~~~~~~~~~~~~~~~~
  59.     $LastChangedDate: $
  60.     $Rev: $
  61.     $Author: $
  62. """


  63. import os, sys, socket, struct, select, time

  64. # From /usr/include/linux/icmp.h; your milage may vary.
  65. ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.


  66. def checksum(source_string):
  67.     """
  68.     I'm not too confident that this is right but testing seems
  69.     to suggest that it gives the same answers as in_cksum in ping.c
  70.     """
  71.     sum = 0
  72.     countTo = (len(source_string)/2)*2
  73.     count = 0
  74.     while count<countTo:
  75.         thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
  76.         sum = sum + thisVal
  77.         sum = sum & 0xffffffff # Necessary?
  78.         count = count + 2

  79.     if countTo<len(source_string):
  80.         sum = sum + ord(source_string[len(source_string) - 1])
  81.         sum = sum & 0xffffffff # Necessary?

  82.     sum = (sum >> 16)  +  (sum & 0xffff)
  83.     sum = sum + (sum >> 16)
  84.     answer = ~sum
  85.     answer = answer & 0xffff

  86.     # Swap bytes. Bugger me if I know why.
  87.     answer = answer >> 8 | (answer << 8 & 0xff00)

  88.     return answer


  89. def receive_one_ping(my_socket, ID, timeout):
  90.     """
  91.     receive the ping from the socket.
  92.     """
  93.     timeLeft = timeout
  94.     while True:
  95.         startedSelect = time.time()
  96.         whatReady = select.select([my_socket], [], [], timeLeft)
  97.         howLongInSelect = (time.time() - startedSelect)
  98.         if whatReady[0] == []: # Timeout
  99.             return

  100.         timeReceived = time.time()
  101.         recPacket, addr = my_socket.recvfrom(1024)
  102.         icmpHeader = recPacket[20:28]
  103.         type, code, checksum, packetID, sequence = struct.unpack(
  104.             "bbHHh", icmpHeader
  105.         )
  106.         if packetID == ID:
  107.             bytesInDouble = struct.calcsize("d")
  108.             timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0]
  109.             return timeReceived - timeSent

  110.         timeLeft = timeLeft - howLongInSelect
  111.         if timeLeft <= 0:
  112.             return


  113. def send_one_ping(my_socket, dest_addr, ID):
  114.     """
  115.     Send one ping to the given >dest_addr<.
  116.     """
  117.     dest_addr  =  socket.gethostbyname(dest_addr)

  118.     # Header is type (8), code (8), checksum (16), id (16), sequence (16)
  119.     my_checksum = 0

  120.     # Make a dummy heder with a 0 checksum.
  121.     header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
  122.     bytesInDouble = struct.calcsize("d")
  123.     data = (192 - bytesInDouble) * "Q"
  124.     data = struct.pack("d", time.time()) + data

  125.     # Calculate the checksum on the data and the dummy header.
  126.     my_checksum = checksum(header + data)

  127.     # Now that we have the right checksum, we put that in. It's just easier
  128.     # to make up a new header than to stuff it into the dummy.
  129.     header = struct.pack(
  130.         "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
  131.     )
  132.     packet = header + data
  133.     my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1


  134. def do_one(dest_addr, timeout):
  135.     """
  136.     Returns either the delay (in seconds) or none on timeout.
  137.     """
  138.     icmp = socket.getprotobyname("icmp")
  139.     try:
  140.         my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
  141.     except socket.error, (errno, msg):
  142.         if errno == 1:
  143.             # Operation not permitted
  144.             msg = msg + (
  145.                 " - Note that ICMP messages can only be sent from processes"
  146.                 " running as root."
  147.             )
  148.             raise socket.error(msg)
  149.         raise # raise the original error

  150.     my_ID = os.getpid() & 0xFFFF

  151.     send_one_ping(my_socket, dest_addr, my_ID)
  152.     delay = receive_one_ping(my_socket, my_ID, timeout)

  153.     my_socket.close()
  154.     return delay


  155. def verbose_ping(dest_addr, timeout = 2, count = 4):
  156.     """
  157.     Send >count< ping to >dest_addr< with the given >timeout< and display
  158.     the result.
  159.     """
  160.     for i in xrange(count):
  161.         print "ping %s..." % dest_addr,
  162.         try:
  163.             delay  =  do_one(dest_addr, timeout)
  164.         except socket.gaierror, e:
  165.             print "failed. (socket error: '%s')" % e[1]
  166.             break

  167.         if delay  ==  None:
  168.             print "failed. (timeout within %ssec.)" % timeout
  169.         else:
  170.             delay  =  delay * 1000
  171.             print "get ping in %0.4fms" % delay
  172.     print


  173. if __name__ == '__main__':
  174.     verbose_ping("heise.de")
  175.     verbose_ping("google.com")
  176.     verbose_ping("a-test-url-taht-is-not-available.com")
  177.     verbose_ping("192.168.1.1")
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP