章工运维 章工运维
首页
  • 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

自动化的Docker容器生成报告脚本

脚本如下

import docker
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Docker客户端配置
DOCKER_CLIENT = docker.from_env()

# 邮件配置
SMTP_SERVER = 'smtp.example.com'
SMTP_PORT = 587
SMTP_USERNAME = 'your_email@example.com'
SMTP_PASSWORD = 'your_password'
SENDER_EMAIL = 'your_email@example.com'
RECEIVER_EMAIL = 'admin@example.com'

# 容器资源使用阈值(百分比)
CPU_THRESHOLD = 80
MEMORY_THRESHOLD = 80

def get_container_stats(container):
    """获取容器的资源使用统计"""
    stats = container.stats(stream=False)
    cpu_stats = stats['cpu_stats']
    precpu_stats = stats['precpu_stats']
    memory_stats = stats['memory_stats']

    cpu_usage = cpu_stats['cpu_usage']['total_usage'] - precpu_stats['cpu_usage']['total_usage']
    system_usage = cpu_stats['system_cpu_usage'] - precpu_stats['system_cpu_usage']
    number_cpus = cpu_stats['online_cpus']
    cpu_percent = (cpu_usage / system_usage) * number_cpus * 100.0

    memory_usage = memory_stats['usage'] / memory_stats['limit'] * 100.0

    return {
        'cpu_percent': cpu_percent,
        'memory_percent': memory_usage
    }

def check_containers():
    """检查所有运行中的容器"""
    containers = DOCKER_CLIENT.containers.list()
    report = []
    for container in containers:
        stats = get_container_stats(container)
        status = "正常"
        if stats['cpu_percent'] > CPU_THRESHOLD or stats['memory_percent'] > MEMORY_THRESHOLD:
            status = "警告"
        
        report.append({
            'name': container.name,
            'id': container.short_id,
            'status': container.status,
            'cpu_usage': f"{stats['cpu_percent']:.2f}%",
            'memory_usage': f"{stats['memory_percent']:.2f}%",
            'overall_status': status
        })
    return report

def restart_container(container_id):
    """重启指定的容器"""
    try:
        container = DOCKER_CLIENT.containers.get(container_id)
        container.restart()
        print(f"容器 {container.name} 已重启")
    except docker.errors.NotFound:
        print(f"容器 {container_id} 未找到")
    except Exception as e:
        print(f"重启容器 {container_id} 时出错: {e}")

def generate_report(container_stats):
    """生成HTML格式的报告"""
    html = """
    <html>
    <head>
        <style>
            table {
                border-collapse: collapse;
                width: 100%;
            }
            th, td {
                border: 1px solid #ddd;
                padding: 8px;
                text-align: left;
            }
            tr:nth-child(even) {background-color: #f2f2f2;}
            th {
                background-color: #4CAF50;
                color: white;
            }
        </style>
    </head>
    <body>
        <h2>Docker容器状态报告</h2>
        <table>
            <tr>
                <th>容器名</th>
                <th>ID</th>
                <th>状态</th>
                <th>CPU使用率</th>
                <th>内存使用率</th>
                <th>总体状态</th>
            </tr>
    """
    for container in container_stats:
        html += f"""
            <tr>
                <td>{container['name']}</td>
                <td>{container['id']}</td>
                <td>{container['status']}</td>
                <td>{container['cpu_usage']}</td>
                <td>{container['memory_usage']}</td>
                <td>{container['overall_status']}</td>
            </tr>
        """
    html += """
        </table>
    </body>
    </html>
    """
    return html

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():
    container_stats = check_containers()
    report = generate_report(container_stats)
    send_email("Docker容器状态报告", report)

    # 检查是否有需要重启的容器
    for container in container_stats:
        if container['overall_status'] == "警告":
            restart = input(f"容器 {container['name']} 资源使用过高,是否重启?(y/n): ")
            if restart.lower() == 'y':
                restart_container(container['id'])

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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
微信 支付宝
上次更新: 2024/12/04, 17:15:49

← 自动化的系统健康检查和报告生成工具 自动化数据库备份和恢复→

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