批量识别文件夹中的show int sw br文本文件,并将识别结果转换成excel文件,从而判断端口状态、端口描述等信息是否符合规定或者完整。
import re
import pandas as pd
import os
import openpyxl
from openpyxl import load_workbook
# 这篇代码用来识别端口状态
folder_path = 'E:/User/Desktop/新建文件夹/'
file_list = os.listdir(folder_path)
def modify_first_column(lst, new_value):
# for row in lst循环遍历lst列表,在每一个循环中,new_value+每一行的第二个元素到尾,实现替换第一个元素的操作。
return [[new_value] + row[1:] for row in lst]
hostname = ''
allDf = pd.DataFrame()
for file_name in file_list:
file_path = os.path.join(folder_path, file_name)
print(file_path)
with open(file_path, 'r') as file:
content = file.read()
match = re.search(r'.*?(?=\#)', content) # 在 content 中搜索主机名
if match:
hostname = match.group(0)
# 识别首为“other”尾为“total”的一段文本,并且不包含首尾。
start_keyword = "Other"
end_keyword = "Total"
# start_index:首字符索引。content.find():返回匹配发哦的关键词的第一个字符索引,len():关键词长度。所以start_index=首关键词后的第一个字符索引。
start_index = content.find(start_keyword) + len(start_keyword)
end_index = content.find(end_keyword)
# 把需要的那段文本提取出来。
text = content[start_index:end_index].strip()
lines = text.strip().split('\n') # 拆分为每行
header = lines[0].split() # 表头
# 将lines数据用split分割为一个二元数组,从第二行开始lines[1:],1:表示的就是从第二行到结束所有的行。
data = [line.split() for line in lines[1:]] # 数据行
print(hostname)
new_data = modify_first_column(data, hostname)
print(new_data)
df = pd.DataFrame(new_data)
allDf = allDf._append(df, ignore_index=True)
print(allDf)
allDf.to_excel('output.xlsx', index=False)