广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python ping 模块
  • 796
分享到

Python ping 模块

模块Pythonping 2023-01-31 07:01:25 796人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

下载地址:下载粘贴一下 v0.2的代码备用#!/usr/bin/env python """ A pure Python ping implementation using raw Socket. Note that ICM

下载地址:下载

粘贴一下 v0.2的代码备用


#!/usr/bin/env python
"""
    A pure Python ping implementation using raw Socket.
    Note that ICMP messages can only be sent from processes running as root.
    Derived from ping.c distributed in linux's netkit. That code is
    copyright (c) 1989 by The Regents of the University of California.
    That code is in turn derived from code written by Mike Muuss of the
    US Army Ballistic Research Laboratory in December, 1983 and
    placed in the public domain. They have my thanks.
    Bugs are naturally mine. I'd be glad to hear about them. There are
    certainly Word - size dependenceies here.
    Copyright (c) Matthew Dixon Cowles, <Http://www.visi.com/~mdc/>.
    Distributable under the terms of the GNU General Public License
    version 2. Provided with no warranties of any sort.
    Original Version from Matthew Dixon Cowles:
      -> ftp://ftp.visi.com/users/mdc/ping.py
    Rewrite by Jens Diemer:
      -> http://www.python-forum.de/post-69122.html#69122
    Rewrite by George Notaras:
      -> http://www.g-loaded.eu/2009/10/30/python-ping/
    Fork by Pierre Bourdon:
      -> http://bitbucket.org/delroth/python-ping/
    Revision history
    ~~~~~~~~~~~~~~~~
    November 22, 1997
    -----------------
    Initial hack. Doesn't do much, but rather than try to guess
    what features I (or others) will want in the future, I've only
    put in what I need now.
    December 16, 1997
    -----------------
    For some reason, the checksum bytes are in the wrong order when
    this is run under Solaris 2.X for SPARC but it works right under
    Linux x86. Since I don't know just what's wrong, I'll swap the
    bytes always and then do an htons().
    December 4, 2000
    ----------------
    Changed the struct.pack() calls to pack the checksum and ID as
    unsigned. My thanks to Jerome Poincheval for the fix.
    May 30, 2007
    ------------
    little rewrite by Jens Diemer:
     -  change socket asterisk import to a nORMal import
     -  replace time.time() with time.clock()
     -  delete "return None" (or change to "return" only)
     -  in checksum() rename "str" to "source_string"
    November 8, 2009
    ----------------
    Improved compatibility with GNU/Linux systems.
    Fixes by:
     * George Notaras -- http://www.g-loaded.eu
    Reported by:
     * Chris Hallman -- http://cdhallman.blogspot.com
    Changes in this release:
     - Re-use time.time() instead of time.clock(). The 2007 implementation
       worked only under Microsoft windows. Failed on GNU/Linux.
       time.clock() behaves differently under the two OSes[1].
    [1] http://docs.python.org/library/time.html#time.clock
    September 25, 2010
    ------------------
    Little modifications by Georgi Kolev:
     -  Added quiet_ping function.
     -  returns percent lost packages, max round trip time, avrg round trip
        time
     -  Added packet size to verbose_ping & quiet_ping functions.
     -  Bump up version to 0.2
"""
__version__ = "0.2"
import os
import select
import socket
import struct
import sys
import time
# From /usr/include/linux/icmp.h; your milage may vary.
ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.
def checksum(source_string):
    """
    I'm not too confident that this is right but testing seems
    to suggest that it gives the same answers as in_cksum in ping.c
    """
    sum = 0
    count_to = (len(source_string) / 2) * 2
    for count in xrange(0, count_to, 2):
        this = ord(source_string[count + 1]) * 256 + ord(source_string[count])
        sum = sum + this
        sum = sum & 0xffffffff # Necessary?
    if count_to < len(source_string):
        sum = sum + ord(source_string[len(source_string) - 1])
        sum = sum & 0xffffffff # Necessary?
    sum = (sum >> 16) + (sum & 0xffff)
    sum = sum + (sum >> 16)
    answer = ~sum
    answer = answer & 0xffff
    # Swap bytes. Bugger me if I know why.
    answer = answer >> 8 | (answer << 8 & 0xff00)
    return answer
def receive_one_ping(my_socket, id, timeout):
    """
    Receive the ping from the socket.
    """
    time_left = timeout
    while True:
        started_select = time.time()
        what_ready = select.select([my_socket], [], [], time_left)
        how_long_in_select = (time.time() - started_select)
        if what_ready[0] == []: # Timeout
            return
        time_received = time.time()
        received_packet, addr = my_socket.recvfrom(1024)
        icmpHeader = received_packet[20:28]
        type, code, checksum, packet_id, sequence = struct.unpack(
            "bbHHh", icmpHeader
        )
        if packet_id == id:
            bytes = struct.calcsize("d")
            time_sent = struct.unpack("d", received_packet[28:28 + bytes])[0]
            return time_received - time_sent
        time_left = time_left - how_long_in_select
        if time_left <= 0:
            return
def send_one_ping(my_socket, dest_addr, id, psize):
    """
    Send one ping to the given >dest_addr<.
    """
    dest_addr  =  socket.gethostbyname(dest_addr)
    # Remove header size from packet size
    psize = psize - 8
    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    my_checksum = 0
    # Make a dummy heder with a 0 checksum.
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, id, 1)
    bytes = struct.calcsize("d")
    data = (psize - bytes) * "Q"
    data = struct.pack("d", time.time()) + data
    # Calculate the checksum on the data and the dummy header.
    my_checksum = checksum(header + data)
    # Now that we have the right checksum, we put that in. It's just easier
    # to make up a new header than to stuff it into the dummy.
    header = struct.pack(
        "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), id, 1
    )
    packet = header + data
    my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
def do_one(dest_addr, timeout, psize):
    """
    Returns either the delay (in seconds) or none on timeout.
    """
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error, (errno, msg):
        if errno == 1:
            # Operation not permitted
            msg = msg + (
                " - Note that ICMP messages can only be sent from processes"
                " running as root."
            )
            raise socket.error(msg)
        raise # raise the original error
    my_id = os.getpid() & 0xFFFF
    send_one_ping(my_socket, dest_addr, my_id, psize)
    delay = receive_one_ping(my_socket, my_id, timeout)
    my_socket.close()
    return delay
def verbose_ping(dest_addr, timeout = 2, count = 4, psize = 64):
    """
    Send `count' ping with `psize' size to `dest_addr' with
    the given `timeout' and display the result.
    """
    for i in xrange(count):
        print "ping %s with ..." % dest_addr,
        try:
            delay  =  do_one(dest_addr, timeout, psize)
        except socket.gaierror, e:
            print "failed. (socket error: '%s')" % e[1]
            break
        if delay  ==  None:
            print "failed. (timeout within %ssec.)" % timeout
        else:
            delay  =  delay * 1000
            print "get ping in %0.4fms" % delay
    print
def quiet_ping(dest_addr, timeout = 2, count = 4, psize = 64):
    """
    Send `count' ping with `psize' size to `dest_addr' with
    the given `timeout' and display the result.
    Returns `percent' lost packages, `max' round trip time
    and `avrg' round trip time.
    """
    mrtt = None
    artt = None
    lost = 0
    plist = []
    for i in xrange(count):
        try:
            delay = do_one(dest_addr, timeout, psize)
        except socket.gaierror, e:
            print "failed. (socket error: '%s')" % e[1]
            break
        if delay != None:
            delay = delay * 1000
            plist.append(delay)
    # Find lost package percent
    percent_lost = 100 - (len(plist) * 100 / count)
    # Find max and avg round trip time
    if plist:
        mrtt = max(plist)
        artt = sum(plist) / len(plist)
    return percent_lost, mrtt, artt
if __name__ == '__main__':
    #verbose_ping("heise.de")
    #verbose_ping("Google.com")
    #verbose_ping("a-test-url-taht-is-not-available.com")
    verbose_ping("www.xd.com")
    print quiet_ping("www.xd.com",count=10)


--结束END--

本文标题: Python ping 模块

本文链接: https://www.lsjlt.com/news/191124.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python ping 模块
    下载地址:下载粘贴一下 v0.2的代码备用#!/usr/bin/env python """ A pure python ping implementation using raw socket. Note that ICM...
    99+
    2023-01-31
    模块 Python ping
  • python模块:smtplib模块
    1.使用本地的sendmail协议进行邮件发送格式(1):smtpObj=smtplib.SMTP([host [,port [,local_hostname]]])host:SMTP服务器主机的IP地址或者是域名port:服务的端口号(默...
    99+
    2023-01-31
    模块 python smtplib
  • Python模块:time模块
    time模块:python中处理时间的基础模块,有时间戳,元组,自定义,三种时间表现形式。python中时间戳的值是以1970年1月1日0点开始计算的,单位是秒。时间戳:就是两个时间差的数值。时区:传说中在开发服务器/客户端程序时,时区不一...
    99+
    2023-01-31
    模块 Python time
  • 使用Python模块:struct模块
    Python没有提供直接的将用户定义的数据类型和文件IO关联起来的功能,但是它提供了struct库(是一个内置库)——我们可以以二进制模式来写这些数据(有趣的是,它真的是设计来讲文本数据写为缓存的) 1)bytes、str...
    99+
    2023-01-31
    模块 Python struct
  • python模块学习----nmap模块
    安装nmap模块:pip install python_nmanmap模块说明:python-nmap是一个帮助使用nmap端口扫描器的python库。它允许轻松操纵nmap扫描结果,并且将是一个完美的选择,为需要自动完成扫描任务的系统管理...
    99+
    2023-01-31
    模块 python nmap
  • python加密模块-hashlib模块
    hashlib模块 用于加密相关的操作,3.X里代替了md5模块和sha模块,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法 (sha比md5 更复杂、md5 不能反解) 具体应用:用于网站防篡改。具...
    99+
    2023-01-31
    模块 python hashlib
  • Python模块
    初步认识 安装完python后,python自带一部分模块,自带的模块又称作内置模块。其中一部分模块在路径Lib下。(这里的文件夹可以看做包,可以把多个模块放进一个包里) 从模块的来源来讲,可以分三种:内置模块、自定义模块(自己定义的)...
    99+
    2023-01-30
    模块 Python
  • python - 模块
    参考:https://www.cnblogs.com/nulige/p/6166205.html一、模块介绍Python Module(模块),就是一个保存了Python代码的文件。模块能定义函数,类和变量。模块里也能包含可执行的代码。文件...
    99+
    2023-01-31
    模块 python
  • python 模块
    python的模块分为2种:1.标准库(不需要安装,直接导入就可以使用的)2.第三方库(必须要手动安装的)先来介绍2个标准库:sys和os#!/usr/bin/env python# coding: utf-8...
    99+
    2023-01-30
    模块 python
  • python-模块
    一:模块的基本认识: 内置模块 内置模块是python自带的功能,在使用内置模块相应功能时,需要先导入再使用    第三方模块 下载-->安装-->使用 1.找到python所在的根目录-->再找到Scrip...
    99+
    2023-01-31
    模块 python
  • Python基础之hashlib模块subprocess模块logging模块
    目录一、hashlib模块基本操作与用法二、subprocess模块简介基本操作与用法三、logging模块简介基本操作与用法一、hashlib模块 什么是哈希模块: hashlib...
    99+
    2022-11-11
    Python hashlib subprocess logging Python 模块基础
  • Python中的sys模块、random模块和math模块
    一、sys运行时环境模块 sys模块负责程序与python解释器的交互,提供了一系列的函数和变量,用于操控python的运行时环境。 用法: sys.argv:命令行参数List,第...
    99+
    2022-11-11
    Python sys模块 random模块 math模块
  • python常见模块之OS模块和time模块
    一、OS模块概述 Python OS模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。 二、常用方法 三、OS模...
    99+
    2022-11-12
    python中的time模块 python中os模块用法 python中time的用法
  • Python时间模块之datetime模块
    目录 简介 函数介绍及运用 date:日期类 1.获取当前时间  2.日期对象的属性 3.date类中时间和时间戳的转换: 4.修改日期使用replace方法  time:时间类  time类操作 datetime:日期时间类 timede...
    99+
    2023-09-12
    python datetime python 日期时间
  • python数学模块(math/decimal模块)
    目录一, math模块2. math库常用函数3.math库使用示例二, decimal模块1. 什么时候使用decimal2. 使用decimal3. decimal使用示例一, ...
    99+
    2022-11-11
    python数学模块math python数学模块decimal
  • Python模块学习之IPy模块
    IP地址规划是网络设计中非常重要的一个环节,规划的好坏会直接影响路由协议算法的效率,包括网络性能、可扩展性等方面,在这个过程当中,免不了要计算大量的IP地址,包括网段、网络掩码、广播地址、子网数、IP类型等。Python提供了一个强大的第...
    99+
    2023-01-31
    模块 Python IPy
  • 【Python模块】Python UUI
    uuid是128位的全局唯一标识符(univeral unique identifier),通常用32位的一个字符串的形式来表现。有时也称guid(global unique identifier)。python中自带了uuid模块来进行u...
    99+
    2023-01-31
    模块 Python UUI
  • Python Scapy Ping
    参考手册:http://phaethon.github.io/scapy/api/usage.html scapy是python的一个库,提供网络协议的构造,请求等scrapy是python的爬虫框架三个层次:1、理解协议2、分析协议3、构...
    99+
    2023-01-31
    Python Scapy Ping
  • 【python】redis模块
    单线程,通过epoll实现高并发,端口6379linux下载地址:http://redis.io/downloadwindows下载地址:https://github.com/MSOpenTech/redis/releases 本文介绍的内...
    99+
    2023-01-31
    模块 python redis
  • Python: httplib2模块
    [+]   httplib2功能介绍:http://code.google.com/p/httplib2/ httplib2实例页面:http://code.google.com/p/httplib2/w/list httplib2问题...
    99+
    2023-01-31
    模块 Python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作