1. #!/usr/bin/env python
  2. #coding=utf-8
  3. import os
  4. import argparse
  5. import socket
  6. import struct
  7. import select
  8. import time
  9.  
  10. ICMP_ECHO_REQUEST = 8 # Platform specific
  11. DEFAULT_TIMEOUT = 2
  12. DEFAULT_COUNT = 4
  13.  
  14. class Pinger(object):
  15. """
  16. Pings to a host -- the Pythonic way
  17. """
  18. def __init__(self, target_host, count=DEFAULT_COUNT, timeout=DEFAULT_TIMEOUT):
  19. self.target_host = target_host
  20. self.count = count
  21. self.timeout = timeout
  22.  
  23. def do_checksum(self, source_string):
  24. """
  25. Verify the packet integritity
  26. """
  27. sum = 0
  28. max_count = (len(source_string)/2)*2
  29. count = 0
  30. while count < max_count: # 分割数据每两比特(16bit)为一组
  31. val = ord(source_string[count + 1])*256 + ord(source_string[count])
  32. sum = sum + val
  33. sum = sum & 0xffffffff
  34. count = count + 2
  35.  
  36. if max_count<len(source_string): # 如果数据长度为基数,则将最后一位单独相加
  37. sum = sum + ord(source_string[len(source_string) - 1])
  38. sum = sum & 0xffffffff
  39.  
  40. sum = (sum >> 16) + (sum & 0xffff) # 将高16位与低16位相加直到高16位为0
  41. sum = sum + (sum >> 16)
  42. answer = ~sum
  43. answer = answer & 0xffff
  44. answer = answer >> 8 | (answer << 8 & 0xff00)
  45. return answer # 返回的是十进制整数
  46.  
  47. def receive_ping(self, sock, ID, timeout):
  48. """
  49. Receive ping from the socket.
  50. """
  51. time_remaining = timeout
  52. while True:
  53. start_time = time.time()
  54. readable = select.select([sock], [], [], time_remaining)
  55. time_spent = (time.time() - start_time)
  56. if readable[0] == []: # Timeout
  57. return
  58.  
  59. time_received = time.time()
  60. recv_packet, addr = sock.recvfrom(1024)
  61. icmp_header = recv_packet[20:28]
  62. type, code, checksum, packet_ID, sequence = struct.unpack(
  63. "bbHHh", icmp_header
  64. )
  65. if packet_ID == ID:
  66. bytes_In_double = struct.calcsize("d")
  67. time_sent = struct.unpack("d", recv_packet[28:28 + bytes_In_double])[0]
  68. return time_received - time_sent
  69.  
  70. time_remaining = time_remaining - time_spent
  71. if time_remaining <= 0:
  72. return
  73.  
  74. def send_ping(self, sock, ID):
  75. #Send ping to the target host
  76. target_addr = socket.gethostbyname(self.target_host)
  77.  
  78. my_checksum = 0
  79.  
  80. # Create a dummy heder with a 0 checksum.
  81. header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
  82. bytes_In_double = struct.calcsize("d")
  83. data = (192 - bytes_In_double) * "Q"
  84. data = struct.pack("d", time.time()) + data
  85.  
  86. # Get the checksum on the data and the dummy header.
  87. my_checksum = self.do_checksum(header + data)
  88. header = struct.pack(
  89. "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
  90. )
  91. packet = header + data
  92. sock.sendto(packet, (target_addr, 1))
  93.  
  94. def ping_once(self):
  95. """
  96. Returns the delay (in seconds) or none on timeout.
  97. """
  98. icmp = socket.getprotobyname("icmp")
  99. try:
  100. sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
  101. except socket.error, (errno, msg):
  102. if errno == 1:
  103. # Not superuser, so operation not permitted
  104. msg += "ICMP messages can only be sent from root user processes"
  105. raise socket.error(msg)
  106. except Exception, e:
  107. print "Exception: %s" %(e)
  108.  
  109. my_ID = os.getpid() & 0xFFFF
  110.  
  111. self.send_ping(sock, my_ID)
  112. delay = self.receive_ping(sock, my_ID, self.timeout)
  113. sock.close()
  114. return delay
  115.  
  116. def ping(self):
  117. """
  118. Run the ping process
  119. """
  120. for i in xrange(self.count):
  121. print "Ping to %s..." % self.target_host,
  122. try:
  123. delay = self.ping_once()
  124. except socket.gaierror, e:
  125. print "Ping failed. (socket error: '%s')" % e[1]
  126. break
  127.  
  128. if delay == None:
  129. print "Ping failed. (timeout within %ssec.)" % self.timeout
  130. else:
  131. delay = delay * 1000
  132. print "Get ping in %0.4fms" % delay
  133.  
  134. if __name__ == '__main__':
  135. parser = argparse.ArgumentParser(description='Python ping')
  136. parser.add_argument('--target-host', action="store", dest="target_host", required=True)
  137. given_args = parser.parse_args()
  138. target_host = given_args.target_host
  139. pinger = Pinger(target_host=target_host, count=5, timeout=5)
  140. pinger.ping()

用python实现ping的更多相关文章

  1. python 多线程 ping

    python 多线程 ping 多线程操作可按如下例子实现 #!/usr/bin/env python #encoding: utf8 import subprocess from threading ...

  2. Python windows ping

    # -*- coding: utf-8 -*- import os # 参考文档: # Ping to a specific IP address using python [duplicate] # ...

  3. HCNP学习笔记之ICMP协议与ping原理以及用Python实现ping

    一.ICMP协议分析 ICMP:Internet控制报文协议.由于IP协议并不是一个可靠的协议,它不保证数据被成功送达,那么,如何才能保证数据的可靠送达呢? 这里就需要使用到一个重要的协议模块ICMP ...

  4. python 多线程ping大量服务器在线情况

    需要ping一个网段所有机器的在线情况,shell脚步运行时间太长,用python写个多线程ping吧,代码如下: #!/usr/bin/python #coding=utf-8 ''' Create ...

  5. python 批量ping服务器

    最近在https://pypi.python.org/pypi/mping/0.1.2找到了一个python包,可以用它来批量ping服务器,它是中国的大神写的,支持单个服务器.将服务器IP写在txt ...

  6. python 批量ping脚本不能用os.system

    os.system(cmd)通过执行命令会得到返回值. ping通的情况下返回值为0. ping不通的情况: 1.请求超时,返回值1 2.无法访问目标主机,返回值为 0,和ping通返回值相同   所 ...

  7. python获取PING结果

    # -*- coding: utf-8 -*- import subprocess import re def get_ping_result(ip_address): p = subprocess. ...

  8. python剑指网络

    >>> #获取hostname ... >>> host_name=socket.gethostname() >>> print "%s ...

  9. python剑指网络篇一

    #coding:utf-8 __author__ = 'similarface' #!/usr/bin/env python import socket #二进制和ASCII互转及其它进制转换 fro ...

随机推荐

  1. Mysql 删除数据表重复行

    准备示例数据 以下sql创建表,并将示例数据插入到用于演示的contacts表中. CREATE TABLE contacts ( id INT PRIMARY KEY AUTO_INCREMENT, ...

  2. Python基础学习总结(一)

    1.变量和数据类型 1.1变量 1.每个变量都存储了一个值——与变量相关联的信息. 2.变量不仅可以为整数或浮点数,还可以是字符串,可以是任意数据类型. 1.1.1变量的命名和使用 变量名只能包含字母 ...

  3. Effective C++ .17 函数调用时的资源管理

    以书上的代码为例 processWidget(shared_ptr<Widget>(new Widget), priority()) 虽然使用了智能指针来管理资源但是,由于参数值计算顺序的 ...

  4. python 数据结构应用

  5. Java—IO流 字符流

    java的文本(char)是16位无符号整数,是字符的unicode编码(双字节编码). 文件是byte byte byte ... 的数据序列. 文本文件是文本(char)序列按照某种编码方案(uf ...

  6. cookie的初识和运用(js和jq)

    cookie是什么 cookie是浏览器提供的一种机制,它将document 对象的cookie属性提供给JavaScript.可以由JavaScript对其进行控制,而并不是JavaScript本身 ...

  7. update_dctcp_alpha

    /* + * Update dctcp alpha based on the ecn bit in the received packet. + * This procedure is called ...

  8. Apache POI使用

    使用apache poi解析 Excel文件: package excellucene; import java.io.File; import java.io.FileInputStream; im ...

  9. 【Leetcode】【Hard】Search in Rotated Sorted Array

    Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 migh ...

  10. Elasticsearch、MongoDB和Hadoop比较

    IT界在过去几年中出现了一个有趣的现象.很多新的技术出现并立即拥抱了“大数据”.稍微老一点的技术也会将大数据添进自己的特性,避免落大部队太远,我们看到了不同技术之间的边际的模糊化.假如你有诸如Elas ...