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和内存的使用率,直到你手动停止它。
立即学习“Python免费学习笔记(深入)”;
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 函数中的其他部分)有时候,你可能只想监控某个特定进程的资源使用情况。 这时候,你需要先找到进程的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等。
psutil还可以监控很多其他的服务器资源,比如:
psutil.disk_usage('/')
psutil.net_io_counters()
psutil.process_iter()
psutil.boot_time()
psutil.users()
可以根据自己的需求,选择合适的API来监控服务器资源。
以上就是如何用Python监控服务器资源?psutil获取CPU内存使用率的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号