用python实现ping
#!/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的更多相关文章
- python 多线程 ping
python 多线程 ping 多线程操作可按如下例子实现 #!/usr/bin/env python #encoding: utf8 import subprocess from threading ...
- Python windows ping
# -*- coding: utf-8 -*- import os # 参考文档: # Ping to a specific IP address using python [duplicate] # ...
- HCNP学习笔记之ICMP协议与ping原理以及用Python实现ping
一.ICMP协议分析 ICMP:Internet控制报文协议.由于IP协议并不是一个可靠的协议,它不保证数据被成功送达,那么,如何才能保证数据的可靠送达呢? 这里就需要使用到一个重要的协议模块ICMP ...
- python 多线程ping大量服务器在线情况
需要ping一个网段所有机器的在线情况,shell脚步运行时间太长,用python写个多线程ping吧,代码如下: #!/usr/bin/python #coding=utf-8 ''' Create ...
- python 批量ping服务器
最近在https://pypi.python.org/pypi/mping/0.1.2找到了一个python包,可以用它来批量ping服务器,它是中国的大神写的,支持单个服务器.将服务器IP写在txt ...
- python 批量ping脚本不能用os.system
os.system(cmd)通过执行命令会得到返回值. ping通的情况下返回值为0. ping不通的情况: 1.请求超时,返回值1 2.无法访问目标主机,返回值为 0,和ping通返回值相同 所 ...
- python获取PING结果
# -*- coding: utf-8 -*- import subprocess import re def get_ping_result(ip_address): p = subprocess. ...
- python剑指网络
>>> #获取hostname ... >>> host_name=socket.gethostname() >>> print "%s ...
- python剑指网络篇一
#coding:utf-8 __author__ = 'similarface' #!/usr/bin/env python import socket #二进制和ASCII互转及其它进制转换 fro ...
随机推荐
- JS实现队列
JS实现队列: 队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表.进行插入操作的端称为队尾 ...
- mysql client does not support authentication
打开mysql 命令行 mysql> alter user 'root'@'localhost' identified with mysql_native_password by '123456 ...
- 前端(五):JavaScript面向对象之内建对象
一.数据类型 js中数据类型分为两种,原始数据累次能够和引用数据类型. 1.原始数据类型 Undefined.Null.Boolean.Number.String是js中五种原始数据类型(primit ...
- 你必须知道的get与post的真正区别
我们会经常看到有人问:http协议中GET请求和POST请求有什么区别~? 这个问题看似很简单,但是不同程度的人会回答出不同的结果.在公司的面试中,也会经常的问及类似这样的问题,看似很简单,但是不同层 ...
- 按需引入antd
使用create-react-app创建项目的时候,官网推荐使用 babel-plugin-import 对antd 按需引入文件.但是配置文件在项目里没有. 可以直接在package.json里加上 ...
- Windows核心编程(第5版)----关闭内核对象
无论怎样创建内核对象,都要向系统指明将通过调用 CloseHandle 来结束对该对象的操作: BOOL CloseHandle(HANDLE hobj); 该函数首先检查调用进程的句柄表,以确保传递 ...
- Python爬虫教程-22-lxml-etree和xpath配合使用
Python爬虫教程-22-lxml-etree和xpath配合使用 lxml:python 的HTML/XML的解析器 官网文档:https://lxml.de/ 使用前,需要安装安 lxml 包 ...
- HBuilder自定义格式化代码
对于代码格式到底为两个空格还是四个空格,可能大家喜欢的都不同,如果你是在使用HBuilder编辑器,那么恭喜你,这两种代码格式你可以轻易的更换.下面贴步骤 1.打开工具—>选项 2.选择HBui ...
- .net CombinedGeometry的合并模式
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="h ...
- python wsgi PEP333 中文翻译
PEP 333 中文翻译 首先说明一下,本人不是专门翻译的,英文水平也不敢拿来献丑.只是这是两年前用python的时候为了自己学习方便而翻译的,记录着笔记自己看看而已.最近翻出来看看觉得还是放出来吧. ...