利用Python实现网络测试的脚本分享
前言
最近同学让我帮忙写一个测试网络的工具。由于工作上的事情,断断续续地拖了很久才给出一个相对完整的版本。其实,我Python用的比较少,所以基本都是边查资料边写程序。
程序的主要逻辑如下:
读取一个excel文件中的ip列表,然后使用多线程调用ping统计每个ip的网络参数,最后把结果输出到excel文件中。
代码如下所示:
#!/usr/bin/envpython
#-*-coding:UTF-8-*-
#File:pingtest_test.py
#Date:2008-09-28
#Author:MichaelField
#ModifiedBy:intheworld
#Date:2017-4-17
importsys
importos
importgetopt
importcommands
importsubprocess
importre
importtime
importthreading
importxlrd
importxlwt
TEST=[
'220.181.57.217',
'166.111.8.28',
'202.114.0.242',
'202.117.0.20',
'202.112.26.34',
'202.203.128.33',
'202.115.64.33',
'202.201.48.2',
'202.114.0.242',
'202.116.160.33',
'202.202.128.33',
]
RESULT={}
defusage():
print"USEAGE:"
print"\t%s-nTEST|excelname[-ttimesofping][-cconcurrentnumber(threadnums)]"%sys.argv[0]
print"\tTEST为简单测试的IP列表"
print"\t-ttimes测试次数;默认为1000;"
print"\t-cconcurrentnumber并行线程数目:默认为10"
print"\t-h|-?,帮助信息"
print"\t输出为当前目录文件ping_result.txt和ping_result.xls"
print"forexample:"
print"\t./ping_test.py-nTEST-t1-c10"
defdiv_list(ls,n):
ifnotisinstance(ls,list)ornotisinstance(n,int):
return[]
ls_len=len(ls)
print'lslength=%s'%ls_len
ifn<=0or0==ls_len:
return[]
ifn>ls_len:
return[]
elifn==ls_len:
return[[i]foriinls]
else:
j=ls_len/n
k=ls_len%n
###j,j,j,...(前面有n-1个j),j+k
#步长j,次数n-1
ls_return=[]
foriinxrange(0,(n-1)*j,j):
ls_return.append(ls[i:i+j])
#算上末尾的j+k
ls_return.append(ls[(n-1)*j:])
returnls_return
defpin(IP):
try:
xpin=subprocess.check_output("ping-n1-w100%s"%IP,shell=True)
exceptException:
xpin='empty'
ms='=[0-9]+ms'.decode("utf8")
print"%s"%ms
print"%s"%xpin
mstime=re.search(ms,xpin)
ifnotmstime:
MS='timeout'
returnMS
else:
MS=mstime.group().split('=')[1]
returnMS.strip('ms')
defcount(total_count,I):
globalRESULT
nowsecond=int(time.time())
nums=0
oknums=0
timeout=0
lostpacket=0.0
total_ms=0.0
avgms=0.0
maxms=-1
whilenums
这段代码参照了别人的实现,虽然不是特别复杂,这里还是简单解释一下。
- excel读写使用了xlrd和xlwt,基本都是使用了一些简单的api。
- 使用了threading实现多线程并发,和POSIX标准接口非常相似。thread_func是线程的处理函数,它的输入包含了一个ip的List,所以在函数内部通过循环处理各个ip。
- 此外,Python的commands在Windows下并不兼容,所以使用了subprocess模块。
到目前为止,我对Python里面字符集的理解还不到位,所以正则表达式匹配的代码并不够强壮,不过目前勉强可以工作,以后有必要再改咯!
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。