textfsm

from concurrent.futures import ThreadPoolExecutor
import netmiko
import os
from threading import Lock
import pandas as pd
from textfsm import TextFSM
import time
from openpyxl import load_workbook


class net_dev():

def __init__(self,excel_name):
try :
os.mkdir("./log")
except:
pass
self.excel_name = excel_name
self.list = [] # 存储log的文件名称
self.pool = ThreadPoolExecutor(10) # 初始化线程数量
self.lock = Lock() # 添加线程锁,避免写入数据丢失
self.path = ("./log") # 创建保存log路径

def file_name_info(self):
file_name = os.listdir(self.path)
self.list = file_name
print(self.list)


def textfsm_1(self):
ntc_templates_path = r'C:\Users\yc\PycharmProjects\netmiko\testfsm学习\ntc_tmplate\\'
result_path = r'C:\Users\yc\PycharmProjects\netmiko\testfsm学习\result\\'

ntc_file = "ZTE_sh_version" # 使用模板名字

result_excel_name = ntc_file + ".xlsx"
#os.chdir(path)
# 新建一个test.xlsx文件
df_tmp = pd.DataFrame(data=None)
with pd.ExcelWriter(str(result_path) + result_excel_name, mode="w") as writer:
df_tmp.to_excel(writer, sheet_name="sheet1", index=False)

for file_name in self.list:
with open(r'C:\Users\yc\PycharmProjects\netmiko\testfsm学习\log\\' + str(file_name) , "r",
encoding="utf-8") as file:
str1 = str(file.read())
info = TextFSM(open(str(ntc_templates_path) + ntc_file )).ParseText(
str1) # 使用textfsm模板
header = (TextFSM(open(str(ntc_templates_path) + ntc_file )).header) # testfsm获取头部
data = info
df = pd.DataFrame(data, columns=header)
print(df)

with pd.ExcelWriter(str(result_path) + result_excel_name, mode="a") as writer:
df.to_excel(writer, sheet_name=str(file_name), index=False)

# 删除默认sheet1
wb = load_workbook(str(result_path) + result_excel_name)
wb.remove(wb["sheet1"])
wb.save(str(result_path) + result_excel_name)

















yc_use = net_dev("设备信息.xlsx")
yc_use.file_name_info()
yc_use.textfsm_1()
posted @ 2023-02-17 10:15  小菜鸟起飞ing  阅读(77)  评论(0编辑  收藏  举报