0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

使用Python进行Ping测试

网络技术干货圈 来源:网络技术干货圈 2024-08-12 17:56 次阅读

转载请注明以下内容:

来源:公众号【网络技术干货圈】

作者:圈圈

ID:wljsghq

在网络工程中,Ping测试是一种常用的网络诊断工具,用于检查网络连接的可达性和响应时间。Ping测试通过向目标主机发送ICMP(Internet Control Message Protocol)请求包,然后等待目标主机返回响应包,从而测量网络的延迟和丢包情况。随着Python编程语言的广泛应用,越来越多的网络工程师开始使用Python进行自动化网络测试和管理任务。本篇文章将详细介绍如何使用Python进行Ping测试,适合网工初学者。

安装Python

首先,确保你的计算机上已安装Python。可以通过以下命令检查Python版本:

python--version

如果未安装Python,可以从Python官方网站https://www.python.org/downloads下载并安装。

在Python中,有多个库可以用来进行Ping测试,其中ping3库是一个简单易用的选择。可以通过pip安装ping3库:

pipinstallping3

确保你的网络环境允许发送ICMP请求。某些操作系统或网络环境可能会限制ICMP流量,这需要相应的权限或配置。

使用ping3库进行Ping测试

基本用法

ping3库提供了一个简单的函数ping,可以用来发送Ping请求并返回响应时间。以下是一个基本示例:

fromping3importping

response_time=ping('baidu.com')
print(f'Responsetime:{response_time}seconds')

wKgaoma53G-AaVZUAABUXbtkmLo864.jpg

这个示例中,我们向baidu.com发送了一个Ping请求,并打印了响应时间。如果目标主机不可达,ping函数会返回None。

wKgZoma53IGAWv2JAAAakguGecA860.jpg

高级用法

ping3库还提供了其他一些功能,例如指定超时时间、数据包大小等。以下是一些高级用法示例:

指定超时时间

可以通过timeout参数指定Ping请求的超时时间(秒):

response_time=ping('baidu.com',timeout=2)
print(f'Responsetime:{response_time}seconds')

指定数据包大小

可以通过size参数指定Ping请求的数据包大小(字节):

response_time=ping('baidu.com',size=64)
print(f'Responsetime:{response_time}seconds')

进行多次Ping测试

可以使用循环进行多次Ping测试,以获取更多的网络性能数据:

foriinrange(5):
response_time=ping('baidu.com')
print(f'Ping{i+1}:{response_time}seconds')

错误处理

在实际网络环境中,Ping请求可能会失败或超时,因此需要进行错误处理。ping3库在目标主机不可达或请求超时时会抛出异常,可以使用try-except块进行处理:

fromping3importping,PingError

try:
response_time=ping('baidu.com',timeout=2)
ifresponse_timeisNone:
print('Targetisunreachable.')
else:
print(f'Responsetime:{response_time}seconds')
exceptPingErrorase:
print(f'Pingfailed:{e}')

实战:构建一个Ping测试工具

接下来,我们将构建一个简单的Ping测试工具,具备以下功能:

从用户输入获取目标主机

执行多次Ping测试

计算并显示平均响应时间、最大响应时间、最小响应时间和丢包率

工具的实现

1. 获取用户输入

首先,编写代码从用户输入获取目标主机:

target=input('Enterthetargethost(e.g.,baidu.com):')

2. 执行多次Ping测试

使用循环进行多次Ping测试,并记录响应时间和失败次数:

fromping3importping

num_tests=10
response_times=[]
failures=0

foriinrange(num_tests):
response_time=ping(target,timeout=2)
ifresponse_timeisNone:
failures+=1
print(f'Ping{i+1}:Requesttimedout.')
else:
response_times.append(response_time)
print(f'Ping{i+1}:{response_time}seconds')

3. 计算并显示统计数据

最后,计算并显示平均响应时间、最大响应时间、最小响应时间和丢包率:

ifresponse_times:
avg_response_time=sum(response_times)/len(response_times)
max_response_time=max(response_times)
min_response_time=min(response_times)
packet_loss=(failures/num_tests)*100

print(f'
Averageresponsetime:{avg_response_time:.2f}seconds')
print(f'Maximumresponsetime:{max_response_time:.2f}seconds')
print(f'Minimumresponsetime:{min_response_time:.2f}seconds')
print(f'Packetloss:{packet_loss:.2f}%')
else:
print('Allrequeststimedout.')

完整代码

将上述步骤整合成一个完整的Python脚本:

fromping3importping,PingError

defmain():
target=input('Enterthetargethost(e.g.,baidu.com):')
num_tests=10
response_times=[]
failures=0

foriinrange(num_tests):
try:
response_time=ping(target,timeout=2)
ifresponse_timeisNone:
failures+=1
print(f'Ping{i+1}:Requesttimedout.')
else:
response_times.append(response_time)
print(f'Ping{i+1}:{response_time}seconds')
exceptPingErrorase:
failures+=1
print(f'Ping{i+1}failed:{e}')

ifresponse_times:
avg_response_time=sum(response_times)/len(response_times)
max_response_time=max(response_times)
min_response_time=min(response_times)
packet_loss=(failures/num_tests)*100

print(f'
Averageresponsetime:{avg_response_time:.2f}seconds')
print(f'Maximumresponsetime:{max_response_time:.2f}seconds')
print(f'Minimumresponsetime:{min_response_time:.2f}seconds')
print(f'Packetloss:{packet_loss:.2f}%')
else:
print('Allrequeststimedout.')

if__name__=='__main__':
main()

扩展功能

使用多线程进行并发Ping测试

为了提高Ping测试的效率,可以使用多线程进行并发Ping测试。Python的threading模块可以帮助实现这一点。

以下是使用多线程进行并发Ping测试的示例:

importthreading
fromping3importping

defping_host(target,results,index):
response_time=ping(target,timeout=2)
results[index]=response_time

defmain():
target=input('Enterthetargethost(e.g.,baidu.com):')
num_tests=10
threads=[]
results=[None]*num_tests

foriinrange(num_tests):
thread=threading.Thread(target=ping_host,args=(target,results,i))
threads.append(thread)
thread.start()

forthreadinthreads:
thread.join()

response_times=[rforrinresultsifrisnotNone]
failures=results.count(None)

ifresponse_times:
avg_response_time=sum(response_times)/len(response_times)
max_response_time=max(response_times)
min_response_time=min(response_times)
packet_loss=(failures/num_tests)*100

print(f'
Averageresponsetime:{avg_response_time:.2f}seconds')
print(f'Maximumresponsetime:{max_response_time:.2f}seconds')
print(f'Minimumresponsetime:{min_response_time:.2f}seconds')
print(f'Packetloss:{packet_loss:.2f}%')
else:
print('Allrequeststimedout.')

if__name__=='__main__':
main()

生成Ping测试报告

可以将Ping测试结果保存到文件中,生成测试报告,以便后续分析。

可以使用Python的csv模块将数据写入CSV文件。

以下是一个生成Ping测试报告的示例:

importcsv
fromping3importping

defmain():
target=input('Enterthetargethost(e.g.,baidu.com):')
num_tests=10
response_times=[]
failures=0

withopen('ping_report.csv','w',newline='')ascsvfile:
fieldnames=['Ping','ResponseTime']
writer=csv.DictWriter(csvfile,fieldnames=fieldnames)
writer.writeheader()

foriinrange(num_tests):
response_time=ping(target,timeout=2)
ifresponse_timeisNone:
failures+=1
print(f'Ping{i+1}:Requesttimedout.')
writer.writerow({'Ping':i+1,'ResponseTime':'Requesttimedout'})
else:
response_times.append(response_time)
print(f'Ping{i+1}:{response_time}seconds')
writer.writerow({'Ping':i+1,'ResponseTime':response_time})

ifresponse_times:
avg_response_time=sum(response_times)/len(response_times)
max_response_time=max(response_times)
min_response_time=min(response_times)
packet_loss=(failures/num_tests)*100

withopen('ping_summary.txt','w')assummaryfile:
summaryfile.write(f'Averageresponsetime:{avg_response_time:.2f}seconds
')
summaryfile.write(f'Maximumresponsetime:{max_response_time:.2f}seconds
')
summaryfile.write(f'Minimumresponsetime:{min_response_time:.2f}seconds
')
summaryfile.write(f'Packetloss:{packet_loss:.2f}%
')

print(f'
Averageresponsetime:{avg_response_time:.2f}seconds')
print(f'Maximumresponsetime:{max_response_time:.2f}seconds')
print(f'Minimumresponsetime:{min_response_time:.2f}seconds')
print(f'Packetloss:{packet_loss:.2f}%')
else:
print('Allrequeststimedout.')

if__name__=='__main__':
main()

wKgZoma53JqACq6JAAG_Jn35sE0173.png

wKgZoma53KmADoBAAACAk8gk_6A485.jpg

运行后响应:

wKgaoma53MCACeXPAABnsWDxY-k315.jpg

额外生成了两个文件:

wKgZoma53M-AT0GrAAAkfiMUM5Y467.jpg

wKgZoma53M-ABFUqAABBUHcZbRA561.jpg

wKgaoma53M-ABv-gAABvq3M9AD4257.jpg

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 编程语言
    +关注

    关注

    10

    文章

    1914

    浏览量

    34362
  • Ping
    +关注

    关注

    0

    文章

    68

    浏览量

    15887
  • python
    +关注

    关注

    53

    文章

    4752

    浏览量

    84044
  • 网络诊断
    +关注

    关注

    0

    文章

    9

    浏览量

    6478

原文标题:网工学Python入门:如何使用 Python 进行 Ping 测试?

文章出处:【微信号:网络技术干货圈,微信公众号:网络技术干货圈】欢迎添加关注!文章转载请注明出处。

收藏 人收藏

    评论

    相关推荐

    为什么用MCAN进行ping测试不起作用怎么解决?

    我想知道为什么我用 MCAN 进行ping 测试不起作用。我已经在 freemaster_cfg.h 中配置了所有设置(我已经引用了 freemaster 驱动程序示例) 我已经检查过我
    发表于 04-19 07:21

    巧用Ping和Traceroute命令排除网络故障

    在分析Ping 和Traceroute 命令工作原理和影响因素的基础上,详细介绍了使用Ping 和Traceroute 命令检查网络连接性、查看信息路径从而排除网络故障的方法和技巧。ping 命令是
    发表于 08-11 08:25 35次下载

    三种不同的“防 Ping”技巧

    三种不同的“防 Ping”技巧 浅析三种不同的“防 Ping”方法   众所周知,Ping命令是一个非常有用的网络命令,大家常用它
    发表于 04-14 13:53 1099次阅读

    ping命令的使用大全(Windows下ping命令的使用)

    ping命令相信大家已经再熟悉不过了,但是能把ping的功能发挥到最大的人却并不是很多,下面就给大家讲一些ping命令的运用。
    的头像 发表于 02-24 10:29 1.4w次阅读

    用以太网 Ping的方式对 MAX10 FPGA 开发套件进行测试

    对MAX10 FPGA 开发套件进行以太网 Ping 测试
    的头像 发表于 06-20 01:00 4745次阅读
    用以太网 <b class='flag-5'>Ping</b>的方式对  MAX10 FPGA 开发套件<b class='flag-5'>进行</b><b class='flag-5'>测试</b>

    ping原理及应用介绍

    Ping程序的实质是利用了ICMP请求回显和回显应答报文,但ARP请求和应答报文也在其中起了非常重要的作用。 Ping的逻辑过程以从PC1 ping PC2(命令:ping 11.1.
    发表于 10-06 14:25 8210次阅读

    ping是什么?ping背后的逻辑是什么样的?是如何实现的?

    我们在遇到网络不通的情况,大家都知道去 ping 一下,看一下网络状况。那你知道「ping」命令后背的逻辑是什么吗?知道它是如何实现的吗?
    的头像 发表于 10-03 12:25 8327次阅读

    Python语言的特点和使用Python对XML文件的数据进行解析说明

    在民用航空电子产品的测试过程中,大部分的测试用例需要编写测试脚本进行自动化测试Python
    发表于 08-28 10:33 6次下载
    <b class='flag-5'>Python</b>语言的特点和使用<b class='flag-5'>Python</b>对XML文件的数据<b class='flag-5'>进行</b>解析说明

    ping命令的作用和原理是什么?

    测试和部署网络通信应用时,我们经常会遇到网络不通的问题。一般都会想到ping一下。那么ping命令的作用和原理到底是什么呢? ping 命令是基于 ICMP 协议来工作的,要明白
    的头像 发表于 03-18 17:21 9393次阅读

    如何利用Python实现快速Ping一个IP网段地址?

    人都要疯掉了,这种情况在大型网络中我们有可能遇到,那怎么办呢?我们今天来看下如何用 python 来实现批量 ping 测试主机。代码如下: #!/usr/bin/python
    的头像 发表于 06-29 15:59 3541次阅读
    如何利用<b class='flag-5'>Python</b>实现快速<b class='flag-5'>Ping</b>一个IP网段地址?

    如何测试Python环境

    在编程中,测试是一项重要的工作,可以帮助我们验证代码的正确性和稳定性。在Python编程环境中,同样需要进行测试来确保Python的安装和配
    的头像 发表于 04-14 12:14 4691次阅读

    PING命令还能这么用?

    今天和你聊聊PING命令。 一般来说,网工们通常会用它来直接ping ip地址,来测试网络的连通情况。 类似这种,ping ip地址或网关,然后pi
    的头像 发表于 05-18 16:43 932次阅读
    <b class='flag-5'>PING</b>命令还能这么用?

    你知道ping命令是如何工作的吗?

    我们用来测试一台机器与另一台机器的网络连通性一般会使用ping命令,那么你知道ping命令是如何工作的吗?ping命令是基于ICMP协议工作的。
    的头像 发表于 05-31 11:40 933次阅读
    你知道<b class='flag-5'>ping</b>命令是如何工作的吗?

    如何使用ping命令测试网络摄像头连通性

    在做智能化弱电项目时,前端摄像头设备安装结束后,我们会对网络摄像头进行调试,调试过程中会遇到前端摄像头没有图像或者图像出来了画面卡顿的现象。我们会采用ping命令来测试网络的连通性和网络承载能力。
    的头像 发表于 08-19 09:48 8304次阅读
    如何使用<b class='flag-5'>ping</b>命令<b class='flag-5'>测试</b>网络摄像头连通性

    Ping测试在不同网段通信中的准确性

    不同网段之间的通信顺畅与否能影响网络的整体性能和业务的正常运行。Ping 测试作为一种常用的网络诊断工具,被广泛用于检测网络连接的可达性。然而,在没有三层交换路由功能的网络中,跨网段的 Ping
    的头像 发表于 07-31 16:15 155次阅读