自动化的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
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