#!/usr/bin/env python
#coding=utf-8
import os
import argparse
import socket
import struct
import select
import time ICMP_ECHO_REQUEST = 8 # Platform specific
DEFAULT_TIMEOUT = 2
DEFAULT_COUNT = 4 class Pinger(object):
"""
Pings to a host -- the Pythonic way
"""
def __init__(self, target_host, count=DEFAULT_COUNT, timeout=DEFAULT_TIMEOUT):
self.target_host = target_host
self.count = count
self.timeout = timeout def do_checksum(self, source_string):
"""
Verify the packet integritity
"""
sum = 0
max_count = (len(source_string)/2)*2
count = 0
while count < max_count: # 分割数据每两比特(16bit)为一组
val = ord(source_string[count + 1])*256 + ord(source_string[count])
sum = sum + val
sum = sum & 0xffffffff
count = count + 2 if max_count<len(source_string): # 如果数据长度为基数,则将最后一位单独相加
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff sum = (sum >> 16) + (sum & 0xffff) # 将高16位与低16位相加直到高16位为0
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer # 返回的是十进制整数 def receive_ping(self, sock, ID, timeout):
"""
Receive ping from the socket.
"""
time_remaining = timeout
while True:
start_time = time.time()
readable = select.select([sock], [], [], time_remaining)
time_spent = (time.time() - start_time)
if readable[0] == []: # Timeout
return time_received = time.time()
recv_packet, addr = sock.recvfrom(1024)
icmp_header = recv_packet[20:28]
type, code, checksum, packet_ID, sequence = struct.unpack(
"bbHHh", icmp_header
)
if packet_ID == ID:
bytes_In_double = struct.calcsize("d")
time_sent = struct.unpack("d", recv_packet[28:28 + bytes_In_double])[0]
return time_received - time_sent time_remaining = time_remaining - time_spent
if time_remaining <= 0:
return def send_ping(self, sock, ID):
#Send ping to the target host
target_addr = socket.gethostbyname(self.target_host) my_checksum = 0 # Create a dummy heder with a 0 checksum.
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
bytes_In_double = struct.calcsize("d")
data = (192 - bytes_In_double) * "Q"
data = struct.pack("d", time.time()) + data # Get the checksum on the data and the dummy header.
my_checksum = self.do_checksum(header + data)
header = struct.pack(
"bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
)
packet = header + data
sock.sendto(packet, (target_addr, 1)) def ping_once(self):
"""
Returns the delay (in seconds) or none on timeout.
"""
icmp = socket.getprotobyname("icmp")
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.error, (errno, msg):
if errno == 1:
# Not superuser, so operation not permitted
msg += "ICMP messages can only be sent from root user processes"
raise socket.error(msg)
except Exception, e:
print "Exception: %s" %(e) my_ID = os.getpid() & 0xFFFF self.send_ping(sock, my_ID)
delay = self.receive_ping(sock, my_ID, self.timeout)
sock.close()
return delay def ping(self):
"""
Run the ping process
"""
for i in xrange(self.count):
print "Ping to %s..." % self.target_host,
try:
delay = self.ping_once()
except socket.gaierror, e:
print "Ping failed. (socket error: '%s')" % e[1]
break if delay == None:
print "Ping failed. (timeout within %ssec.)" % self.timeout
else:
delay = delay * 1000
print "Get ping in %0.4fms" % delay if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Python ping')
parser.add_argument('--target-host', action="store", dest="target_host", required=True)
given_args = parser.parse_args()
target_host = given_args.target_host
pinger = Pinger(target_host=target_host, count=5, timeout=5)
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. quartz---定时器(配置注解方式&配置xml方式)

    本入门案例基于spring和quartz整合完成. 第一步:创建maven工程,导入spring和quartz相关依赖 第二步:创建任务类 第三步:在spring配置文件中配置任务类 第四步:在spr ...

  2. Spring Cloud实战之初级入门(五)— 配置中心服务化与配置实时刷新

    目录 1.环境介绍 2.配置中心服务化 2.1 改造mirco-service-spring-config 2.2 改造mirco-service-provider.mirco-service-con ...

  3. jquery ajaxFileUpload异步上传文件

    ajaxFileUpload.js 很多同名的,因为做出来一个很容易. 我用的是这个:https://github.com/carlcarl/AjaxFileUpload 下载地址在这里:http:/ ...

  4. servlet开发(四)之ServletContext

    接上一篇. 2.3.4 利用ServletContext对象读取资源文件 比如我们要读取web项目中的配置文件. 项目目录结构如下: 使用ServletContext对象读取资源文件的示例代码如下: ...

  5. Java 异常的处理方式--throws和try catch

    异常的第一种处理方式throws. 看以下例子: import java.io.*;public class ExceptionTest04{ public static void main(Stri ...

  6. hibernate cascade的真正含义

    hibernate cascade 是 @OneToOne @OneToMany @ManyToOne @ManyToMany等注解的属性,表示级联操作. /** * (Optional) The o ...

  7. SSIS 和 SSRS自制Template

    可以使用VS 制作一个SSIS 的Package. 路径:C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssembl ...

  8. 浅谈JavaScript之function用括号包起来

    (function a(){}) (命名函数表达式)会返回这个函数(不会执行),但是在括号外面无法调用该函数,需要一个变量接收这个函数,var fun = (function a(){}),一般这个用 ...

  9. SpringBoot2.0+Mybatis+PageHelper+Redis实现缓存

    1.在maven引入相关的依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactI ...

  10. 【Machine Learning】决策树之简介(1)

    Content 1.decision tree representation 2.ID3:a top down learning algorithm 3.expressiveness of data ...