使用python 实现,调用系统ping命令,统计多次ping包的统计结果,存储在excel 表中。
python版本:Python2
#coding=utf-8
import os
import re
import xlwt
import time
#设置表格样式
def set_stlye(name,height,bold=False):
#初始化样式
style = xlwt.XFStyle()
#创建字体
font = xlwt.Font()
font.bold = bold
font.colour_index = 4
font.height = height
font.name =name
style.font = font
return style
def create_excel():
f = xlwt.Workbook()
#创建sheet1
sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True)
row0 = [u'times',u'transmitted',u'received',u'duplicates',u'loss']
for i in range(0,len(row0)):
sheet1.write(0,i,row0[i],set_stlye("Time New Roman",220,True))
return f,sheet1
def save_excel(f,filname):
f.save(filname)
def write_excel(sheet,row,col,data):
sheet.write(row,col,data)
def func_ping(ip,count,ping_index, sheet):
times = ping_index + 1
process = os.popen("ping "+ip+" -c "+count)
#process = os.popen("ping 192.168.1.1 -c 1")
output = process.read()
process.close()
#print(output)
pattern='\d+ +packets transmitted'
m = re.search(pattern, output)
if m:
print(m.group())
transmit = re.search('\d', m.group())
if transmit:
write_excel(sheet,times,1,transmit.group())
pattern='\d+ +received'
m = re.search(pattern, output)
if m:
print(m.group())
transmit = re.search('\d', m.group())
if transmit:
write_excel(sheet,times,2,transmit.group())
pattern='\d+ +duplicates'
m = re.search(pattern, output)
if m:
print(m.group())
transmit = re.search('\d', m.group())
if transmit:
write_excel(sheet,times,3,transmit.group())
pattern='\d+% +packet loss'
m = re.search(pattern, output)
if m:
print(m.group())
transmit = re.search('\d', m.group())
if transmit:
write_excel(sheet,times,4,transmit.group())
write_excel(sheet,times,0,times)
if __name__ == '__main__':
f,sheet = create_excel()
for i in range(20):
func_ping("192.168.1.1","100",i,sheet)
excel_file_name="ping_data_"+time.strftime("%Y-%m-%d-%H%M%S", time.localtime())+".xls"
save_excel(f,excel_file_name)