系统巡检Python生成word报告🧫

系统巡检Python生成word报告🧫


 

 

1. 安装psutil和python-docx模块

[root@localhost ~]# pip install psutil python-docx

 

2. 编写python脚本

#/usr/bin/env python
import psutil
from docx import Document
from docx.shared import Pt, Inches
from datetime import datetime

def generate_system_report():
    # 创建文档
    doc = Document()

    # 设置中文字体
    chinese_font = '宋体'

    # 添加标题
    title_style = doc.styles['Title']
    title_paragraph = doc.add_paragraph()
    title_run = title_paragraph.add_run('系统巡检报告')
    title_run.bold = True
    title_run.font.size = Pt(24)
    title_run.font.name = chinese_font
    title_paragraph.style = title_style

    # 添加日期
    date_paragraph = doc.add_paragraph(datetime.now().strftime("巡检日期:%Y年%m月%d日 %H:%M:%S"))
    date_paragraph.alignment = 1  # 居中对齐
    date_paragraph.runs[0].font.name = chinese_font

    # 添加表格:CPU使用情况
    add_table(doc, chinese_font, 'CPU使用情况', [
        ('指标', '数值'),
        ('CPU使用率', f'{psutil.cpu_percent(interval=1)}%')
    ])

    # 添加表格:内存使用情况
    mem = psutil.virtual_memory()
    add_table(doc, chinese_font, '内存使用情况', [
        ('指标', '数值'),
        ('总内存', f'{mem.total / (1024.0 ** 3):.2f} GB'),
        ('可用内存', f'{mem.available / (1024.0 ** 3):.2f} GB'),
        ('已用内存', f'{mem.used / (1024.0 ** 3):.2f} GB'),
        ('内存使用率', f'{mem.percent}%')
    ])

    # 添加表格:磁盘使用情况
    add_table(doc, chinese_font, '磁盘使用情况', [
        ('指标', '数值'),
        ('总空间', f'{psutil.disk_usage("/").total / (1024.0 ** 3):.2f} GB'),
        ('已用空间', f'{psutil.disk_usage("/").used / (1024.0 ** 3):.2f} GB'),
        ('剩余空间', f'{psutil.disk_usage("/").free / (1024.0 ** 3):.2f} GB'),
        ('磁盘使用率', f'{psutil.disk_usage("/").percent}%')
    ])

    # 添加表格:所有分区的磁盘使用情况
    partitions = psutil.disk_partitions()
    add_table(doc, chinese_font, '文件系统状态', [
        ('挂载点', '总空间 (GB)', '已用空间 (GB)', '剩余空间 (GB)', '使用率 (%)')
    ] + [
        (
            partition.mountpoint,
            f'{psutil.disk_usage(partition.mountpoint).total / (1024.0 ** 3):.2f}',
            f'{psutil.disk_usage(partition.mountpoint).used / (1024.0 ** 3):.2f}',
            f'{psutil.disk_usage(partition.mountpoint).free / (1024.0 ** 3):.2f}',
            f'{psutil.disk_usage(partition.mountpoint).percent}%'
        )
        for partition in partitions
    ])

    # 添加表格:系统负载
    load_avg = psutil.getloadavg()
    add_table(doc, chinese_font, '系统负载', [
        ('指标', '数值'),
        ('1分钟平均负载', f'{load_avg[0]:.2f}'),
        ('5分钟平均负载', f'{load_avg[1]:.2f}'),
        ('15分钟平均负载', f'{load_avg[2]:.2f}')
    ])

    # 添加表格:网络信息
    net_io = psutil.net_io_counters()
    add_table(doc, chinese_font, '网络信息', [
        ('指标', '数值'),
        ('发送字节数', f'{net_io.bytes_sent / (1024.0 ** 2):.2f} MB'),
        ('接收字节数', f'{net_io.bytes_recv / (1024.0 ** 2):.2f} MB'),
        ('发送数据包数', f'{net_io.packets_sent} 个'),
        ('接收数据包数', f'{net_io.packets_recv} 个')
    ])

    # 生成文件名
    filename = f'system_patrol_report_{datetime.now().strftime("%Y%m%d")}.docx'

    # 保存文档
    doc.save(filename)

def add_table(doc, chinese_font, title, data):
    # 添加标题
    heading = doc.add_heading(level=2)
    heading_run = heading.add_run(title)
    heading_run.bold = True
    heading_run.font.size = Pt(16)
    heading_run.font.name = chinese_font

    # 添加表格
    table = doc.add_table(rows=1, cols=len(data[0]), style='Table Grid')
    set_table_column_widths(table, 1.5, 2)

    # 添加表头
    hdr_cells = table.rows[0].cells
    for i, header in enumerate(data[0]):
        hdr_cells[i].text = header
        paragraph = hdr_cells[i].paragraphs[0]
        paragraph.paragraph_format.alignment = 1  # 居中对齐
        run = paragraph.runs[0]
        run.font.name = chinese_font
        run.bold = True
        run.font.size = Pt(12)

    # 添加数据行
    for item in data[1:]:
        row_cells = table.add_row().cells
        for i, cell_data in enumerate(item):
            row_cells[i].text = str(cell_data)
            paragraph = row_cells[i].paragraphs[0]
            paragraph.paragraph_format.alignment = 1  # 居中对齐
            run = paragraph.runs[0]
            run.font.name = chinese_font
            run.font.size = Pt(10)

def set_table_column_widths(table, *widths):
    for col_idx, width in enumerate(widths):
        table.columns[col_idx].width = Inches(width)

# 调用函数生成报告
generate_system_report()

 

posted @ 2024-07-19 12:36  Noleaf  阅读(137)  评论(0编辑  收藏  举报