章工运维 章工运维
首页
  • linux
  • windows
  • 中间件
  • 监控
  • 网络
  • 存储
  • 安全
  • 防火墙
  • 数据库
  • 系统
  • docker
  • 运维工具
  • other
  • elk
  • K8S
  • ansible
  • Jenkins
  • GitLabCI_CD
  • 随笔
  • 面试
  • 工具
  • 收藏夹
  • Shell
  • python
  • golang
友链
  • 索引

    • 分类
    • 标签
    • 归档
    • 首页 (opens new window)
    • 关于我 (opens new window)
    • 图床 (opens new window)
    • 评论 (opens new window)
    • 导航栏 (opens new window)
周刊
GitHub (opens new window)

章工运维

业精于勤,荒于嬉
首页
  • linux
  • windows
  • 中间件
  • 监控
  • 网络
  • 存储
  • 安全
  • 防火墙
  • 数据库
  • 系统
  • docker
  • 运维工具
  • other
  • elk
  • K8S
  • ansible
  • Jenkins
  • GitLabCI_CD
  • 随笔
  • 面试
  • 工具
  • 收藏夹
  • Shell
  • python
  • golang
友链
  • 索引

    • 分类
    • 标签
    • 归档
    • 首页 (opens new window)
    • 关于我 (opens new window)
    • 图床 (opens new window)
    • 评论 (opens new window)
    • 导航栏 (opens new window)
周刊
GitHub (opens new window)
  • python

    • python基础

    • FastAPI

    • python每日练习脚本

      • 监控系统资源情况并发送邮件告警
      • 备份文件并发送邮件通知
      • 批量修改主机名
      • 监控文件夹大小变化并发送邮件通知
      • 批量修改多台主机的SSH端口
      • 监控Web服务器的HTTP响应状态码并发送警报
      • 自动化服务部署脚本01
      • 自动化服务部署脚本02
      • 自动化的系统健康检查和报告生成工具
      • 自动化的Docker容器生成报告脚本
      • 自动化数据库备份和恢复
    • python3给防火墙添加放行
    • python生成部署脚本
    • python将多个文件内容输出到一个文件中
    • 使用 Aligo 定时备份服务器文件
    • python监控日志文件并发送钉钉告警
    • python监控数据库脚本并发送钉钉告警
    • 使用python编写自动化发布脚本
    • 查询redis列表某个元素
    • centos7安装python3
    • python环境管理工具介绍
    • conda安装和镜像源配置
    • pip更换国内源
    • python爬虫
    • python环境启动服务报错缺少glibc库版本
    • 监控目录或文件变化
    • 批量更改文件
    • python引用数据库
  • shell

  • go

  • 编程
  • python
  • python每日练习脚本
章工运维
2024-07-16

自动化的系统健康检查和报告生成工具

脚本如下

import psutil
import platform
import datetime
import socket
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 邮件配置
SMTP_SERVER = 'smtp.qq.com'
SMTP_PORT = 587
SMTP_USERNAME = 'xxx@qq.com'
SMTP_PASSWORD = 'xxx'
SENDER_EMAIL = 'xxx@qq.com'
RECEIVER_EMAIL = 'xxx@163.com'

def get_size(bytes, suffix="B"):
    """
    缩放字节单位到合适的大小
    """
    factor = 1024
    for unit in ["", "K", "M", "G", "T", "P"]:
        if bytes < factor:
            return f"{bytes:.2f}{unit}{suffix}"
        bytes /= factor

def check_cpu():
    """检查CPU使用情况"""
    cpu_usage = psutil.cpu_percent(interval=1)
    return f"CPU使用率: {cpu_usage}%"

def check_memory():
    """检查内存使用情况"""
    mem = psutil.virtual_memory()
    return f"内存使用: {get_size(mem.used)}/{get_size(mem.total)} ({mem.percent}%)"

def check_disk():
    """检查磁盘使用情况"""
    partitions = psutil.disk_partitions()
    disk_info = []
    for partition in partitions:
        try:
            partition_usage = psutil.disk_usage(partition.mountpoint)
        except PermissionError:
            continue
        disk_info.append(f"磁盘 {partition.device}: {get_size(partition_usage.used)}/{get_size(partition_usage.total)} ({partition_usage.percent}%)")
    return "\n".join(disk_info)

def check_network():
    """检查网络连接情况"""
    hostname = socket.gethostname()
    ip_address = socket.gethostbyname(hostname)
    return f"主机名: {hostname}\nIP地址: {ip_address}"

def generate_report():
    """生成系统健康报告"""
    report = f"""
    <html>
    <head>
        <title>系统健康报告</title>
        <style>
            body {{ font-family: Arial, sans-serif; }}
            .section {{ margin-bottom: 20px; }}
        </style>
    </head>
    <body>
        <h1>系统健康报告</h1>
        <p>生成时间: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</p>
        
        <div class="section">
            <h2>系统信息</h2>
            <p>操作系统: {platform.system()} {platform.version()}</p>
            <p>Python版本: {platform.python_version()}</p>
        </div>
        
        <div class="section">
            <h2>CPU信息</h2>
            <p>{check_cpu()}</p>
        </div>
        
        <div class="section">
            <h2>内存信息</h2>
            <p>{check_memory()}</p>
        </div>
        
        <div class="section">
            <h2>磁盘信息</h2>
            <p>{check_disk()}</p>
        </div>
        
        <div class="section">
            <h2>网络信息</h2>
            <p>{check_network()}</p>
        </div>
    </body>
    </html>
    """
    return report

def send_email(subject, body):
    """发送邮件"""
    msg = MIMEMultipart()
    msg['From'] = SENDER_EMAIL
    msg['To'] = RECEIVER_EMAIL
    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'html'))

    try:
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()
            server.login(SMTP_USERNAME, SMTP_PASSWORD)
            server.send_message(msg)
        print("健康报告已通过邮件发送")
    except Exception as e:
        print(f"发送邮件时出错: {e}")

def main():
    report = generate_report()
    send_email("系统健康报告", report)

if __name__ == "__main__":
    main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
微信 支付宝
上次更新: 2024/12/04, 17:15:49

← 自动化服务部署脚本02 自动化的Docker容器生成报告脚本→

最近更新
01
shell脚本模块集合
05-13
02
生活小技巧(认知版)
04-29
03
生活小技巧(防骗版)
04-29
更多文章>
Theme by Vdoing | Copyright © 2019-2025 | 点击查看十年之约 | 鄂ICP备2024072800号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式