用 Python 实现快速 Ping 一个 IP 网段地址!
DevOps技术栈
共 12516字,需浏览 26分钟
· 2021-07-10
原文链接:www.yjsec.com/2020/11/07
ping 命令是我们检查网络中最常用的命令,作为网络人员,基本上每天都会用到,可以很好地帮助我们分析和判定网络故障;
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import argparse
import socket
import struct
import select
import time
ICMP_ECHO_REQUEST = 8 # Platform specific
DEFAULT_TIMEOUT = 0.1
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:
val = source_string[count + 1]*256 + 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)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receive_pong(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()) + 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 + 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 as e:
if e.errno == 1:
# Not superuser, so operation not permitted
e.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() & 0xFFFF
self.send_ping(sock, my_ID)
delay = self.receive_pong(sock, my_ID, self.timeout)
sock.close()
return delay
def 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])
break
if delay == None:
print ("Ping failed. (timeout within %ssec.)" % self.timeout)
else:
delay = delay * 1000
print("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)
测试如下:
- END -
推荐阅读 31天拿下Kubernetes含金量最高的CKA+CKS证书! 最新Kubernetes实战指南:从零到架构师的进阶之路 Linux 这些工具堪称神器! 下一代Docker镜像构建神器 BuildKit 面试数十家Linux运维工程师,总结了这些面试题(含答案) 记一次 Linux 被入侵,服务器变 “矿机”~ 七年老运维实战中的 Shell 开发经验总结 快速入门 Ansible 自动化运维工具 | 16张图 最强整理!常用正则表达式速查手册 搭建一套完整的企业级 K8s 集群(v1.20,kubeadm方式) 12年资深运维老司机的成长感悟
点亮,服务器三年不宕机
评论
盘点一个使用超级鹰识别验证码并自动登录的案例
点击上方“Python共享之家”,进行关注回复“资源”即可获赠Python学习资料今日鸡汤江上几人在,天涯孤棹还。大家好,我是皮皮。一、前言前几天在Python钻石交流群【静惜】问了一个Python实现识别验证码并自动登录的问题,提问截图如下:验证码的截图如下所示:二、实现过程这里大家激烈的探讨,【
IT共享之家
0
Python列表知识应知应会
点击上方“Go语言进阶学习”,进行关注回复“Go语言”即可获赠从入门到进阶共10本电子书今日鸡汤只在此山中,云深不知处。一、前言 在Python程序开发中,列表(List)经常会使用。假设一个班里有50个学生现需要统计每一个学生的总成绩情况,如果不使用列
Go语言进阶学习
0
Eiten 一个构建投资组合的好帮手
Eiten是Tradytics的一个开源工具包,它实现了各种统计和算法投资策略,如Eigen组合、最小方差组合、最大夏普比率组合和基于遗传算法的组合。Eiten允许你用自己的股票组合建立自己的投资组合。Eiten中自带的严格测试框架使你能够对你的投资组合更有自信。1.准备开始之前,你要确保Pytho
Python实用宝典
0
Python 字符串应该用双引号还是单引号?
转载来源:洪尔摩斯PyCharm升级至 2023.2版本后,经常弹出来一个提示问我要不要试一下Black formatter。试了一下,这个Black formatter 很有个性,特别喜欢换行。我的一个文件用PyCharm自带的代码整理器整理完之后是500行左右,然后再用Black整理就变成600
菜鸟学Python
0
delorean,一个超级实用的 Python 库!
作者通常周更,为了不错过更新,请点击上方“Python碎片”,“星标”公众号大家好,今天为大家分享一个超级实用的 Python 库 - delorean。Github地址:https://github.com/myusuf3/delorean/时间在计算机科学和软件开发中是一个至关重要的概念。Pyt
Python 碎片
0
五一Python抢票神器来了
还在为五一回家抢不到火车票发愁吗?今天介绍一个Python抢票神器,希望对你有帮助。Py12306是一个流行的开源项目,旨在帮助用户更便捷地查询和预订中国铁路12306网站上的火车票。以下是使用Py12306的基本步骤和一些注意事项:安装与环境准备安装Python: 确保你的系统中安装了Python
Python小二
1
我用这10招,能减少了80%的BUG
将Python客栈设为“星标⭐”第一时间收到最新资讯前言对于大部分程序员来说,主要的工作时间是在开发和修复BUG。有可能修改了一个BUG,会导致几个新BUG的产生,不断循环。那么,有没有办法能够减少BUG,保证代码质量,提升工作效率?答案是肯定的。如果能做到,我们多出来的时间,多摸点鱼,做点自己喜欢
Python客栈
0
PyPy为什么能让Python比C还快?一文了解内在机制
我的小册:(小白零基础用Python量化股票分析小册) ,原价299,限时特价2杯咖啡,满100人涨10元。来源:机器之心「如果想让代码运行得更快,您应该使用 PyPy。」—— Python 之父 Guido van Rossum对于研究人员来说,迅速把想法代码化并查看其是否行得通至关重要。Pyth
菜鸟学Python
0