ping包统计

使用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)
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值