当我们在做巡检时,需要从一批show文本中提取一些关键指标保存到表格或数据库,这时可以尝试用python来处理,思路大概就是先从各个文本提取hostname,再进行数据分块,接着对相关命令(比如show version,show inventory)的输出信息做正则提取,最后写入表格或数据库保存。

1、读取文本所在文件夹,获取文本路径,写入列表

def GetPath():for root, dirs, files in os.walk(u'Before'):for file in files:#文件相对路径(提取文件名)#xlsname = file.decode('gbk').encode('utf-8')filename = file#.split('.')[0]filename_list.append(filename)#文件绝对路径xlspath = os.path.join(root,file)dirpath_list.append(xlspath)print(len(dirpath_list))

2、主函数调用多线程方式对每个文件进行解析

    #执行多线程threads_data_list =[]   #多线程结果列表while filename_list:filename = filename_list[0]filename_list.pop(0)dirpath = dirpath_list[0]dirpath_list.pop(0)t = MyThread(main,(filename,dirpath), main.__name__)threads_data_list.append(t)for thr in threads_data_list:thr.start()for thr in threads_data_list:if thr.is_alive():thr.join()time.sleep(0.2)

3、读取文本内容,提取hostname,重新命名文本。比如处理的是show version 及 show inventory命令的输出信息。

def main(filename,dirpath):output  = open (dirpath, 'r',encoding='utf-8-sig')output = output.read()hostname = 'N/A'#提取hostname,重新命名txtmatchObj = re.search( r'hostname (\S+)', output, re.M|re.I)if matchObj:hostname = matchObj.group(1)new_filename_list.append(hostname)WriteTxt(hostname,output)else:error_list.append(dirpath)ip = '  'matchObj1 = re.search('((\d+\.){3}\d+)',filename,re.M|re.I)if matchObj1:ip = matchObj1.group(1)#记录文本文件名称转换记录echo_info = filename + '>>>' +hostname +'>>>' + ip + '\n'with open('.\\log.txt','a')as td:td.write(echo_info)if hostname != 'N/A':deivce_data = GetData(output,hostname,ip)return deivce_datadef GetData(info,hostname,ip):if re.search(r'www\.cisco\.com',info,re.I):brand='cisco'#print(brand)piece_data_list = info.split('{}[#|>|\]]'.format(hostname))#print(hostname)for piece_data in piece_data_list:data_info_dic={'hostname':hostname,'ip':ip,'HareWareModel':'','UpTime':'','SystemImageFile':'','SystemSN':'','show inventory':''}#查看模块命令show inventory,多行匹配,多个匹配模式,返回元组列表if re.search('show inventory|inv.*',piece_data,re.I|re.M):# #show inventory : NAME,PID,SNdata_info_dic = data_parsing.parsing('show inventory',piece_data,data_info_dic)#命令show version,单行匹配if re.search('show version|ver.*',piece_data,re.I|re.M):#show version : HareWareModel,UpTime,System image file,SystemSNdata_info_dic = data_parsing.parsing('show version',piece_data,data_info_dic)breakreturn data_info_dic#WriteExcel(data_info_dic)

4、数据写入表格

主函数中调用WriteExcel#数据写入表格WriteExcel(threads_data_list)def WriteExcel(all_data_list):rownum = 2rownum1 = 2number = 1#新建表格过程Workbook = xlwt.Workbook()         #创建工作簿alignment = xlwt.Alignment()alignment.horz = 0x02    # 0x01(左端对齐)、0x02(水平方向上居中对齐)、0x03(右端对齐)alignment.vert = 0x01    # 0x00(上端对齐)、 0x01(垂直方向上居中对齐)、0x02(底端对齐)alignment.wrap = 1    # 设置自动换行# 初始化样式style = xlwt.XFStyle()style.alignment = alignmentsheet1 = Workbook.add_sheet(u'设备信息',cell_overwrite_ok=True) #创建sheetrow0 = ['序号','主机名','管理IP','型号','运行时间','软件版本','序列号']row1 = ['Name','PID','序列号']#创建表头信息for i in range(0,len(row0)):sheet1.write_merge(0,1,i,i,row0[i],style)sheet1.write_merge(0,0,len(row0),len(row0)+2,'模块信息',style)for i in range(0,len(row1)):sheet1.write(1,i+len(row0),row1[i],style)for i in range(0,len(row0)+len(row1)):sheet1.col(i).width = 20 * 256      #xlwt中列宽的值表示方法:默认字体0的1/256为衡量单位。xlwt创建时使用的默认宽度为2960,既11个字符0的宽度,所以我们在设置列宽时可以用如下方法:width = 256 * 20    #256为衡量单位,20表示20个字符宽度for data in all_data_list:if data.get_result() != None:data_info_dic =data.get_result()try:hostname = data_info_dic['hostname']ip = data_info_dic['ip']data_list = data_info_dic['show inventory']len_num = len(data_list)if len_num >=1:# write_merge(a,b,c,d,message)函数将从第a行到第b行的第c列到第d列的单元格合并,并填入内容messagesheet1.write_merge(rownum,rownum+len_num-1,0,0,str(number),style)  #第一列sheet1.write_merge(rownum,rownum+len_num-1,1,1,hostname,style)  #第一列sheet1.write_merge(rownum,rownum+len_num-1,2,2,ip,style)sheet1.write_merge(rownum,rownum+len_num-1,3,3,data_info_dic['HareWareModel'],style)sheet1.write_merge(rownum,rownum+len_num-1,4,4,data_info_dic['UpTime'],style)sheet1.write_merge(rownum,rownum+len_num-1,5,5,data_info_dic['SystemImageFile'],style)sheet1.write_merge(rownum,rownum+len_num-1,6,6,data_info_dic['SystemSN'],style)for data in data_list:for k in range(0,len(data)):# 每行,逐列写入sheet1.write(rownum1,k+len(row0),data[k].strip(),style)rownum1 += 1rownum = rownum + len_numelse:sheet1.write(rownum,0,str(number),style)sheet1.write(rownum,1,hostname,style)  #第一列sheet1.write(rownum,2,ip,style)sheet1.write(rownum,3,data_info_dic['HareWareModel'],style)sheet1.write(rownum,4,data_info_dic['UpTime'],style)sheet1.write(rownum,5,data_info_dic['SystemImageFile'],style)sheet1.write(rownum,6,data_info_dic['SystemSN'],style)rownum += 1rownum1 += 1number += 1except Exception as e:print(str(e))print(data.get_result())Workbook.save('./demo2.xls') #保存文件 

表格格式如图所示 :

 demo code:https://download.csdn.net/download/bosshuang666/87647395

欢迎交流!

python批量处理网络设备的巡检文本文件,提取关键指标写入表格或数据库相关推荐

  1. python批量提取word指定内容_使用python批量读取word文档并整理关键信息到excel表格的实例...

    目标 最近实验室里成立了一个计算机兴趣小组 倡议大家多把自己解决问题的经验记录并分享 就像在CSDN写博客一样 虽然刚刚起步 但考虑到后面此类经验记录的资料会越来越多 所以一开始就要做好模板设计(如下 ...

  2. Python批量运行Gprmax仿真并快速提取雷达波走时和振幅

    Python批量运行Gprmax仿真并快速提取雷达波走时和振幅 使用gprmax仿真模拟时,通常在cmd窗口写命令,运行结果保存的文件夹不能任意选择,这样很不方便.尤其是在做钻孔电磁波仿真时,需要大量 ...

  3. Python爬取百度百科,BeautifulSoup提取关键信息

    本文主要爬取演员杨幂的百度百科,用到的python库有:requests和BeautifulSoup 主要内容共分为以下两个方面: 1. 用requests爬取网页内容 2. 用BeautifulSo ...

  4. python批量读取文件内容_Python 文本文件内容批量抽取实例

    Python新手编写脚本处理数据,各种心酸各种语法查找,以此留念! 原始数据格式如下图所示: 这里是一个人脸测试数据,其中每行第一个为测试图片编号,后面为Top 7图片编号及其对应的评分,即与测试图片 ...

  5. python批量提取word指定内容到excel_(转)用python批量读取word文档并整理关键信息到excel表格...

    目标 最近实验室里成立了一个计算机兴趣小组 倡议大家多把自己解决问题的经验记录并分享 就像在CSDN写博客一样 虽然刚刚起步 但考虑到后面此类经验记录的资料会越来越多 所以一开始就要做好模板设计(如下 ...

  6. python 批量读取xlsx并合并_python合并多个excel表格数据-python如何读取多个excel合并到一个excel中...

    python如何读取多个excel合并到一个excel中 思路 利用python xlrd包读取excle文件,然后将文件内容存入一个列表中,再利用xlsxwriter将内容写入到一个新的excel文 ...

  7. python批量打印excel 按照顺序_从txt文件写入excel2007,后台打印顺序正常,但是打开excel实际数据没有按照顺序排列...

    openpyxl的版本是:openpyxl-2.5.0a1 我的目的是将txt中的文本写入excel中,其实是一个自己想实现的一个小功能 但是从txt文件写入excel2007,后台打印顺序正常,但是 ...

  8. python批量提取pdf的数据_Python批量提取PDF文件中文本的脚本

    本文实例为大家分享了Python批量提取PDF文件中文本的具体代码,供大家参考,具体内容如下 首先需要执行命令pip install pdfminer3k来安装处理PDF文件的扩展库. import ...

  9. Python批量提取Word文件题库中的答案

    问题描述:假设有Word文件"Python题库.docx"中有若干Python题目(目前有1000道,已在公众号内分享第一期1000道Python题库系列分享一(17道))和对应的 ...

最新文章

  1. Redux 的黑魔法
  2. GitHub 重磅更新:无限私有仓库免费使用
  3. 玩转Mixly – 3、Arduino AVR编程 之 控制
  4. 《MVC 系列》- 控制器数据传递
  5. android ButterKnife的简单使用
  6. java多线程 cpu分配_java多线程总结(转载)
  7. 图像处理:给验证码图片做降噪处理及数据清洗
  8. 判断字符串和数组是否为空
  9. empinfo Oracle数据库,Oracle:其他数据库对象
  10. 【FLUENT案例】04:利用DDPM+DEM模拟鼓泡流化床
  11. 基于GLBP协议的医院网络规划与设计 文档+申请表+任务书+开题报告+中期检查+文献综述+PPT+周进展+网络拓扑及配置
  12. Unity Spine 换装方案
  13. 如何看待越来越多年轻人追捧「摸鱼哲学」,拒绝努力的年轻人真比老一辈活得更通透吗?
  14. 人脸识别face recognition
  15. QCharts QValueAxis使用
  16. 1087 花括号展开
  17. 电脑开机后电脑连接正常几分钟后网络连接失败
  18. 28-1.kubernetes
  19. CCIE与HCIE哪个含金量高些?
  20. keyshot渲染玻璃打光_Keyshot渲染材质 灯光 等高级技巧

热门文章

  1. 青岛科技大学计算机毕业生去向,青岛科技大学好就业吗?附青岛科技大学就业率最高的专业名单...
  2. stem科学实验课关联
  3. 学习python的第三节课:基础数据
  4. 中南大学计算机学院的辅导员,我院田生伟院长一行访问中南大学计算机学院
  5. Tcp三次握手、四次分手,Socket再看不懂,你砍我
  6. 重磅 | Stratifyd发布《2021金融服务行业客户体验报告》
  7. DZNT论坛 3.6.711删除用户各种错解决方案
  8. 通过车牌号查车辆信息的方法有哪些?
  9. 360°全景影像数据流图和代码走读
  10. Floodlight模块简介