系統巡檢Python生成word報告🧫

Noleaf發表於2024-07-19

系統巡檢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()

相關文章