ping 命令是我们检查网络中最常用的命令,作为网络人员,基本上每天都会用到,可以很好地帮助我们分析和判定网络故障;

如果有 10 设备,100 台设备,1000 台设备怎么办?一个个 ping 过去人都要疯掉了,这种情况在大型网络中我们有可能遇到,那怎么办呢?我们今天来看下如何用 python 来实现批量 ping 测试主机。

代码如下:

#!/usr/bin/python3
# -*- coding: utf-8 -*-import os
import argparse
import socket
import struct
import select
import timeICMP_ECHO_REQUEST = 8 # Platform specific
DEFAULT_TIMEOUT = 0.1
DEFAULT_COUNT = 4class Pinger(object):""" Pings to a host -- the Pythonic way"""def __init__(self, target_host, count=DEFAULT_COUNT, timeout=DEFAULT_TIMEOUT):self.target_host = target_hostself.count = countself.timeout = timeoutdef do_checksum(self, source_string):"""  Verify the packet integritity """sum = 0max_count = (len(source_string)/2)*2count = 0while count < max_count:val = source_string[count + 1]*256 + source_string[count]sum = sum + valsum = sum & 0xffffffffcount = count + 2if max_count<len(source_string):sum = sum + ord(source_string[len(source_string) - 1])sum = sum & 0xffffffffsum = (sum >> 16)  +  (sum & 0xffff)sum = sum + (sum >> 16)answer = ~sumanswer = answer & 0xffffanswer = answer >> 8 | (answer << 8 & 0xff00)return answerdef receive_pong(self, sock, ID, timeout):"""Receive ping from the socket."""time_remaining = timeoutwhile True:start_time = time.time()readable = select.select([sock], [], [], time_remaining)time_spent = (time.time() - start_time)if readable[0] == []: # Timeoutreturntime_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_senttime_remaining = time_remaining - time_spentif time_remaining <= 0:returndef 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()) + bytes(data.encode('utf-8'))# 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 + datasock.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 as e:if e.errno == 1:# Not superuser, so operation not permittede.msg +=  "ICMP messages can only be sent from root user processes"raise socket.error(e.msg)except Exception as e:print("Exception: %s" %(e))my_ID = os.getpid() & 0xFFFFself.send_ping(sock, my_ID)delay = self.receive_pong(sock, my_ID, self.timeout)sock.close()return delaydef ping(self):"""Run the ping process"""for i in range(self.count):print ("Ping to %s..." % self.target_host,)try:delay  =  self.ping_once()except socket.gaierror as e:print ("Ping failed. (socket error: '%s')" % e[1])breakif delay  ==  None:print ("Ping failed. (timeout within %ssec.)" % self.timeout)else:delay = delay * 1000print("Get pong in %0.4fms" % delay)if __name__ == '__main__':alive = []host_prefix = '192.168.242.'for i in range(1, 255):host = host_prefix + str(i)pinger = Pinger(target_host=host)delay = pinger.ping_once()if delay == None:print("Ping %s 失败,超时2秒" % host)else:print("ping %s = %s ms" % (host, round(delay * 1000, 4)))alive.append(host)# time.sleep(0.5)

测试如下:

EOF

干货分享,一个 IP 网段地址!Python相关推荐

  1. python 公众号文章发布_分享一个牛逼的Python项目:公众号文章爬虫

    我订阅了近 100 个公众号,有时候想再找之前读过的文章,发现搜索起来特别困难,如果忘了收藏,估计得找半小时,更让人无语的是,文章已经发布者删除,或者文章因违规被删除.那么有没有这样的爬虫,可以将公众 ...

  2. python爬取公众号阅读量_分享一个牛逼的Python项目:公众号文章爬虫

    我订阅了近 100 个公众号,有时候想再找之前读过的文章,发现搜索起来特别困难,如果忘了收藏,估计得找半小时,更让人无语的是,文章已经发布者删除,或者文章因违规被删除.那么有没有这样的爬虫,可以将公众 ...

  3. 分享一个ip反查域名的网站

    http://dns.aizhan.com/ 输入你要反查域名的ip地址,会列出各个域名的访问状态. 转载于:https://blog.51cto.com/xjcf00/1640730

  4. 分享一个网址 上面的 python 库比官网还全........ .

    来自: http://blog.csdn.net/rav009/article/details/14978419 http://www.lfd.uci.edu/~gohlke/pythonlibs

  5. python定期自动运行_干货分享 | 适合 Python 入门的 8 款强大工具,不会就你还不知道吧!...

    点击上方"人工智能Corner","星标或置顶公众号" 干货分享,第一时间送达 Python是一种开源的编程语言,可用于Web编程.数据科学.人工智能以及许多科 ...

  6. 从零开发一个非常有意思的 Python 项目:电子考勤系统

    今天给大家分享一个比较有意思的Python应用,用 Python 写了一个电子考勤系统,源码已在文章全部给出,记得点赞收藏哦- 文章目录 项目简介 技术交流 答题要求 附加功能 导入模块 加载数据 登 ...

  7. 分享一个python cookbook的在线教程地址

    分享一个python cookbook的在线教程地址: http://python3-cookbook.readthedocs.org/zh_CN/latest/ 翻译者:熊能 转载于:https:/ ...

  8. 干货分享,使用python爬虫构建免费代理IP池

    在使用python爬虫的时候,经常会遇见所要爬取的网站采取了反爬取技术,高强度.高效率地爬取网页信息常常会给网站服务器带来巨大压力,所以同一个IP反复爬取同一个网页,就很可能被封,那如何解决呢?使用代 ...

  9. python怎么模拟浏览器交互_干货分享:python爬虫模拟浏览器的两种方法实例分析(赶紧收藏)...

    今天为大家带来的内容是:干货分享:python爬虫模拟浏览器的两种方法实例分析(赶紧收藏) 文章主要介绍了python爬虫模拟浏览器的两种方法,结合实例形式分析了Python爬虫模拟浏览器的两种常见操 ...

最新文章

  1. Windows XP Mode
  2. Verilog功能模块——符号位扩展
  3. 怎么开发一个npm包
  4. 制作镜像包时遇到的模块加载错误的问题
  5. MongoDB无法注册windows服务问题解决 Error connecting to the Service Control Manager: 拒绝访问 Mongodb M
  6. linux下配置ndk路径,NDK调试arm-linux-androideabi-addr2line工具的使用
  7. 把Sublime Text3从windwos移到ubunut上
  8. 解决性能问题中SQL Server警报:SQL Server警报基础
  9. shell脚本:监控MySQL服务是否正常
  10. dagger2 注入_Android依赖注入– Dagger 2
  11. 《Linux/UNIX OpenLDAP实战指南》——1.4 OpenLDAP目录条目概述
  12. NYOJ-47 过河问题
  13. 计算机usb 不显示错误的是,电脑插入U盘不显示USB Mass storage device感叹号
  14. 做一个广告业务后台需要几天,5天吗?不,用PhalApi开源框架,1天就能做好
  15. canvas教程16-滚动的车轮
  16. 高一必修一 第一单元
  17. 3682. 宇恒棋 (华师月赛)
  18. 给20块钱买可乐,每瓶可乐3块钱,喝完之后退瓶子可以换回1块钱,问最多可以喝到多少瓶可乐
  19. 从Eclipse中导入项目到AndroidStudio中
  20. Spatial Zadoff-Chu modulation for rapid beam alignment in mmWave phased arrays

热门文章

  1. 瑞萨单片机iap串口升级boot工程的构建-学习记录
  2. git branch -D 大写的D 删除分支
  3. 网易云课堂学习-zk集群
  4. C语言中的字符变量和字符常量
  5. [硬件选型] 光源及照明方式的选择
  6. 毛线剪藏(MaoXian Web Clipper)的安装、设置和使用
  7. linux实操——XShell5远程登录以及XFtp5远程文件操作教程
  8. 《生命不息,折腾不止》 罗永浩著
  9. Linux----SUID提权复现
  10. 【汉字编码几个字节】