暂无图片
暂无图片
3
暂无图片
暂无图片
暂无图片

使用Python自动生成word巡检报告【三】-完整代码篇

原创 red_hope 2020-09-13
2168

经过使用使用Python自动生成word巡检报告【一】(https://www.modb.pro/db/31880)及使用Python自动生成word巡检报告【二】(https://www.modb.pro/db/32044)两篇文章对利用Python的编写word巡检报告的讲解,在前面的基础上,本章贡献全部代码:

import re
from docx import Document
import os
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml


# ###标题用大写数字函数,正规
def num_to_char(num):
    """数字转中文"""
    num = str(num)
    new_str = ""
    num_dict = {"0": u"零", "1": u"一", "2": u"二", "3": u"三", "4": u"四", "5": u"五", "6": u"六", "7": u"七", "8": u"八",
                "9": u"九"}
    listnum = list(num)
    # print(listnum)
    shu = []
    for i in listnum:
        # print(num_dict[i])
        shu.append(num_dict[i])
    new_str = "".join(shu)
    # print(new_str)
    return new_str


# ####返回标题,巡检日志中我们一般用英文,但是文档必须是中文的
def get_title(flag_fg):
    if 'Check file system' in flag_fg:
        xj_title_hs = '主机文件系统巡检'
    elif 'Check CPU &MEM' in flag_fg:
        xj_title_hs = 'CPU、内存检查'
    elif 'Check ETH' in flag_fg:
        xj_title_hs = '网卡状态检查'
    elif 'Check /var/log/message' in flag_fg:
        xj_title_hs = '主机日志检查'
    elif 'Check transparent_hugepage' in flag_fg:
        xj_title_hs = 'LINUX系统透明大页检查'
    elif 'Check nr_hugepages' in flag_fg:
        xj_title_hs = 'LINUX系统大页开启情况检查'
    elif 'Check meminfo' in flag_fg:
        xj_title_hs = 'PLNOCHECK'
    elif 'Check enforce' in flag_fg:
        xj_title_hs = 'LINUX安全模式打开情况'
    elif 'Check firewalld' in flag_fg:
        xj_title_hs = 'LINUX防火墙打开情况'
    elif 'Check syslimits' in flag_fg:
        xj_title_hs = 'PLNOCHECK'
    elif 'Check CLUALERT log' in flag_fg:
        xj_title_hs = '数据库集群日志检查'
    elif 'Check DBALERT log' in flag_fg:
        xj_title_hs = '数据库日志检查'
    elif 'panduan grid oracle_home' in flag_fg:
        xj_title_hs = 'PLNOCHECK'
    elif 'Begin check crs if have' in flag_fg:
        xj_title_hs = 'PLNOCHECK'
    elif 'Check crs status' in flag_fg:
        xj_title_hs = '集群状态检查'
    elif 'panduan oracle oracle_home' in flag_fg:
        xj_title_hs = 'PLNOCHECK'
    elif 'Check DB ' in flag_fg:
        xj_title_hs = '数据库详细检查'
    else:
        xj_title_hs = flag_fg
    return xj_title_hs


# #目录遍历函数,用于读取目录下所有文件
def list_dir(file_dir):
    dir_list = os.listdir(file_dir)
    file_r = []
    for cur_file in dir_list:
        # 准确获取一个txt的位置,利用字符串的拼接
        path = os.path.join(file_dir, cur_file)
        if cur_file.startswith("check") & path.endswith(".log"):
            file_r.append(path)
    return file_r


# 知识库函数-简例子
def get_knowledge(str_input):
    str_output = []  # 没发现什么,就先输出巡检正常。
    str_output_text='巡检正常'
    if '[always] madvise never' in str_input:
        str_output  = ['Linux未关闭透明大页,根据ORACLE安装要求,应关闭透明大页,提升ORACLE 内存及IO读写性能','1111111']
    elif 'always madvise [never]' in str_input:
        str_output  = ['巡检正常:Linux已关闭透明大页','000000']
    else:
        str_output  = ['巡检正常','000000']
    return str_output


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # 打开文件
    # file = "D:\\专业知识\oracle\\周工作总结\\2020-0821\\checkdb_aix_mapsdb1_2020-08-21.log"
    #file_dir = 'C:\\Users\pc\\Desktop\\数据库巡检脚本\\'
    file_dir= 'D:\\巡检2020-9-8\\'
    file_all = list_dir(file_dir)
    for i in range(len(file_all)):
        file = file_all[i]
        file_full = file.split('\\')
        file_str = ''
        ##截取文件名称,用于报告输出
        for value in file_full:
            file_name = value
            new_filename = file_name.split('.')
            for new_value in new_filename:
                if 'check' in new_value:
                    print(new_value)
                    file_str = new_value

        f = open(file, 'r', encoding='UTF-8')

        # 读取分隔符,写入到list类型的number变量中,关键字就是####
        lines = f.readlines()
        number = []
        for lss in lines:
            m = re.findall(r"####", lss)
            if m:
                number.append(lss)
        f.close()  ##用完文件关闭是个好习惯

        # 创建一个world实例
        Docx = Document()  #
        p = Docx.add_heading(level=0)
        run = p.add_run('ORACLE巡检报告')
        # 以下是字体颜色字体等设置
        # run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
        # Docx.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
        # run.font.color.rgb = RGBColor(0, 0, 0)

        # 再打开文件,开始正式读取巡检内容
        f = open(file, 'r', encoding='UTF-8')
        buff = f.read()

        # 将多余的SQL>格式去掉
        # for a in buff:
        buff = buff.replace('SQL>', '')
        buff = buff.replace('\r', '')
        ###现在表格中输出巡检数据库基本信息:
        Docx.add_heading("数据库基本信息", level=1)

        # 做个表格,放入巡检机器的基本信息
        table_1 = Docx.add_table(rows=3, cols=2, style='Table Grid')
        hdr_cells_0 = table_1.rows[0].cells
        hdr_cells_0[0].text = 'IP地址:'

        hdr_cells_1 = table_1.rows[1].cells
        hdr_cells_1[0].text = '主机名称:'
        host_s = "HOSTNAME#"
        host_n = "Release#"
        pat = re.compile(host_s + '(.*)' + host_n, re.S)
        host_n = pat.findall(buff)
        hdr_cells_1[1].text = host_n

        hdr_cells_2 = table_1.rows[2].cells
        hdr_cells_2[0].text = '巡检日期:'
        time_s = "checktime#"
        time_n = "HOSTNAME#"
        pat = re.compile(time_s + '(.*)' + time_n, re.S)
        check_time = pat.findall(buff)
        hdr_cells_2 = table_1.rows[2].cells
        hdr_cells_2[1].text = check_time

        xj_title = "" #world的各级标题变量
        wt_all = [] # 记录巡检发现问题的列表
        # 开始循环读取巡检结果
        for j in range(len(number)):
            k = j + 1  # 只所以要设置K,是为了房子和j溢出,因为最后一行是没有j+1的
            if k < len(number):
                fenge1 = number[j]
                fenge2 = number[j + 1]
                fenge1 = fenge1.replace('\n', '')
                print(f'{k}:开始查找{fenge1}相关的内容')
                xj_title = get_title(fenge1)
                if xj_title == 'PLNOCHECK':
                    # 遇到不检查项目,跳出本次循环
                    continue
                daxie = num_to_char(k)
                title = f'巡检{daxie}:{xj_title}'
                Docx.add_heading(title, level=1)
                Docx.add_heading("1、巡检结果:", level=2)
                pat = re.compile(fenge1 + '(.*)' + fenge2, re.S)
                result = pat.findall(buff)
                for match1 in result:
                    match1 = match1.replace('\n\n', '')
                    ##中间多余的信息删除
                    match1 = match1[:match1.rfind('CHECKJCSQL')]
                    match1 = match1.rstrip()
                    match1 = match1.lstrip()
                    ##中间多余的信息删除完成
                    table = Docx.add_table(rows=1, cols=1, style='Table Grid')
                    hdr_cells = table.rows[0].cells
                    hdr_cells[0].text = match1

                Docx.add_heading("2、分析结果:", level=2)
                table2 = Docx.add_table(rows=1, cols=1, style='Table Grid')
                hdr_cells2 = table2.rows[0].cells
                # 利用知识库对巡检内容match1进行知识检索
                str_output_now = get_knowledge(match1)
                # 将巡检内容显示到表格中
                hdr_cells2[0].text = str_output_now[0]
                if str_output_now[1]=='1111111':
                    shading_elm_1 = parse_xml(r'<w:shd {} w:fill="D9E2F3"/>'.format(nsdecls('w')))
                    hdr_cells2[0]._tc.get_or_add_tcPr().append(shading_elm_1)
                    # run.font.color.rgb = RGBColor(0, 0, 0)
                    # 同时,如发现我问题,记录在List wt_all中,便于在问题汇总中自动列出
                    wt_all.append(str_output_now[0])


        Docx.add_heading("问题汇总:", level=1)
        for k in range(len(wt_all)):
            Docx.add_heading(f'{k+1}.{wt_all[k]}',level=3)
        Docx.save(f'D:\巡检2020-9-8\ORACLE巡检报告{file_str.upper()}.docx')
        f.close()

如果大家敢兴趣,可以添加微信qq113075398交流。

最后修改时间:2021-06-17 08:52:51
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论