Python监控服务器:psutil获取CPU内存使用率
时间:2025-06-30 17:16:13 257浏览 收藏
使用Python和psutil库可以精确监控服务器资源,例如CPU和内存使用率,是系统运维的利器。本文将深入探讨如何利用psutil获取服务器各项指标,并通过代码示例详细讲解:如何获取CPU整体及每个核心的使用率,以及如何计算一段时间内的平均CPU使用率;如何监控特定进程的CPU和内存占用情况;如何将监控数据通过matplotlib或plotly等库进行可视化,实时展示CPU和内存的使用趋势;更重要的是,如何设置阈值,并通过smtplib发送邮件,实现服务器资源异常的告警机制,及时发现并解决问题。此外,psutil还支持监控磁盘使用率、网络流量、系统启动时间、用户登录信息等多种服务器资源,为服务器的稳定运行保驾护航。
1.使用psutil库可精确监控服务器资源,如CPU和内存使用率。2.通过psutil.cpu_percent(interval=1)获取整体CPU使用率,设置interval参数提高准确性;3.使用psutil.cpu_percent(percpu=True)获取每个CPU核心的使用情况;4.利用psutil.cpu_times()记录时间差值,计算一段时间内的平均CPU使用率;5.通过psutil.Process(pid)监控特定进程的CPU和内存使用率,并结合process_iter()查找PID;6.借助matplotlib或plotly等库将数据可视化,例如绘制实时折线图展示CPU和内存使用趋势;7.设置阈值并通过smtplib发送邮件实现告警机制,及时通知异常情况;8.psutil还支持监控磁盘使用率、网络流量、系统启动时间、用户登录信息等多种服务器资源。
监控服务器资源,特别是CPU和内存使用率,用Python来说,最直接也是最常用的库就是psutil
。 它简单易用,能提供相当全面的系统信息。

安装psutil
非常简单:pip install psutil
。

import psutil import time def get_cpu_usage(): """获取CPU使用率""" return psutil.cpu_percent(interval=1) # interval=1 表示每秒采样一次 def get_memory_usage(): """获取内存使用率""" memory = psutil.virtual_memory() return memory.percent def main(): try: while True: cpu_usage = get_cpu_usage() memory_usage = get_memory_usage() print(f"CPU 使用率: {cpu_usage}%") print(f"内存 使用率: {memory_usage}%") time.sleep(2) # 每隔2秒更新一次 except KeyboardInterrupt: print("监控已停止") if __name__ == "__main__": main()
这个脚本会持续打印CPU和内存的使用率,直到你手动停止它。
如何更精确地监控CPU使用率?
psutil.cpu_percent()
函数已经相当好用了,但有时候你可能需要更细粒度的信息,比如每个CPU核心的使用情况。 psutil.cpu_percent(percpu=True)
可以返回一个列表,包含每个CPU核心的使用率。

另外,如果需要监控一段时间内的平均CPU使用率,可以考虑使用psutil.cpu_times()
和psutil.cpu_times_percent()
。 cpu_times()
返回的是CPU在不同状态(user, system, idle等)下运行的时间,而cpu_times_percent()
返回的是这些时间占总时间的百分比。 通过记录一段时间内的cpu_times()
,然后计算差值,可以得到更精确的平均CPU使用率。
import psutil import time def get_average_cpu_usage(interval=5): """获取一段时间内的平均CPU使用率""" cpu_usage_before = psutil.cpu_times() time.sleep(interval) cpu_usage_after = psutil.cpu_times() idle_diff = cpu_usage_after.idle - cpu_usage_before.idle total_diff = sum(cpu_usage_after) - sum(cpu_usage_before) cpu_usage = 100.0 * (total_diff - idle_diff) / total_diff if total_diff > 0 else 0.0 return cpu_usage # ... (省略 main 函数中的其他部分)
如何监控特定进程的CPU和内存使用率?
有时候,你可能只想监控某个特定进程的资源使用情况。 这时候,你需要先找到进程的PID(进程ID),然后通过psutil.Process(pid)
创建一个Process
对象。
import psutil import time def get_process_cpu_memory(pid): """获取指定进程的CPU和内存使用率""" try: process = psutil.Process(pid) cpu_usage = process.cpu_percent(interval=1) memory_usage = process.memory_percent() return cpu_usage, memory_usage except psutil.NoSuchProcess: return None, None def main(): pid = 1234 # 替换成你要监控的进程的PID try: while True: cpu_usage, memory_usage = get_process_cpu_memory(pid) if cpu_usage is not None and memory_usage is not None: print(f"进程 {pid} CPU 使用率: {cpu_usage}%") print(f"进程 {pid} 内存 使用率: {memory_usage}%") else: print(f"进程 {pid} 不存在") time.sleep(2) except KeyboardInterrupt: print("监控已停止") if __name__ == "__main__": main()
要找到进程的PID,可以使用psutil.process_iter()
遍历所有进程,然后根据进程名或其他属性来筛选。
如何将监控数据可视化?
单纯的打印数据可能不够直观,将监控数据可视化可以更方便地发现问题。 可以使用matplotlib
或plotly
等库来绘制图表。 例如,可以创建一个简单的折线图,显示CPU和内存使用率随时间的变化。
import psutil import time import matplotlib.pyplot as plt def main(): cpu_usage_history = [] memory_usage_history = [] timestamp_history = [] try: while True: cpu_usage = psutil.cpu_percent(interval=1) memory_usage = psutil.virtual_memory().percent cpu_usage_history.append(cpu_usage) memory_usage_history.append(memory_usage) timestamp_history.append(time.strftime("%H:%M:%S")) # 记录时间戳 # 只保留最近60个数据点 if len(cpu_usage_history) > 60: cpu_usage_history.pop(0) memory_usage_history.pop(0) timestamp_history.pop(0) # 绘制图表 plt.clf() # 清除当前图形 plt.plot(timestamp_history, cpu_usage_history, label="CPU Usage") plt.plot(timestamp_history, memory_usage_history, label="Memory Usage") plt.xlabel("Time") plt.ylabel("Usage (%)") plt.title("CPU and Memory Usage") plt.legend() plt.xticks(rotation=45, ha="right") # 旋转x轴标签,使其更易读 plt.tight_layout() # 自动调整子图参数,使其填充整个图像区域 plt.pause(0.1) # 暂停0.1秒,更新图表 except KeyboardInterrupt: print("监控已停止") plt.show() # 显示最终图表 if __name__ == "__main__": main()
这个例子使用了matplotlib
来实时绘制CPU和内存使用率的折线图。 记得安装matplotlib
: pip install matplotlib
。
如何设置资源使用率的告警?
监控的目的是为了及时发现问题,因此设置告警机制非常重要。 可以设置一个阈值,当CPU或内存使用率超过这个阈值时,发送邮件或短信告警。
import psutil import time import smtplib from email.mime.text import MIMEText def send_email(subject, body, sender_email, sender_password, receiver_email): """发送邮件""" message = MIMEText(body) message['Subject'] = subject message['From'] = sender_email message['To'] = receiver_email try: with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server: # 使用 Gmail SMTP 服务器 server.login(sender_email, sender_password) server.sendmail(sender_email, receiver_email, message.as_string()) print("邮件发送成功") except Exception as e: print(f"邮件发送失败: {e}") def main(): cpu_threshold = 80 # CPU 使用率阈值 memory_threshold = 90 # 内存使用率阈值 sender_email = "your_email@gmail.com" # 你的邮箱 sender_password = "your_password" # 你的邮箱密码或应用专用密码 receiver_email = "recipient_email@example.com" # 接收告警的邮箱 try: while True: cpu_usage = psutil.cpu_percent(interval=1) memory_usage = psutil.virtual_memory().percent if cpu_usage > cpu_threshold: subject = "CPU 使用率告警" body = f"CPU 使用率已超过阈值 ({cpu_threshold}%): {cpu_usage}%" send_email(subject, body, sender_email, sender_password, receiver_email) if memory_usage > memory_threshold: subject = "内存 使用率告警" body = f"内存 使用率已超过阈值 ({memory_threshold}%): {memory_usage}%" send_email(subject, body, sender_email, sender_password, receiver_email) time.sleep(60) # 每隔60秒检查一次 except KeyboardInterrupt: print("监控已停止") if __name__ == "__main__": main()
这个例子使用了Gmail的SMTP服务器来发送邮件。 你需要替换your_email@gmail.com
、your_password
和recipient_email@example.com
为你的真实邮箱地址和密码。 注意,如果你的Gmail账号开启了“两步验证”,你需要使用“应用专用密码”而不是你的Gmail密码。
另外,还可以使用其他的告警方式,比如发送短信、调用API等。
除了CPU和内存,还能监控哪些服务器资源?
psutil
还可以监控很多其他的服务器资源,比如:
- 磁盘使用率:
psutil.disk_usage('/')
- 网络流量:
psutil.net_io_counters()
- 进程列表:
psutil.process_iter()
- 系统启动时间:
psutil.boot_time()
- 用户登录信息:
psutil.users()
可以根据自己的需求,选择合适的API来监控服务器资源。
到这里,我们也就讲完了《Python监控服务器:psutil获取CPU内存使用率》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于Python,CPU使用率,告警,psutil,内存使用率的知识点!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
346 收藏
-
127 收藏
-
372 收藏
-
244 收藏
-
391 收藏
-
225 收藏
-
174 收藏
-
339 收藏
-
317 收藏
-
384 收藏
-
139 收藏
-
463 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习