登录
首页 >  文章 >  python教程

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还支持监控磁盘使用率、网络流量、系统启动时间、用户登录信息等多种服务器资源。

如何用Python监控服务器资源?psutil获取CPU内存使用率

监控服务器资源,特别是CPU和内存使用率,用Python来说,最直接也是最常用的库就是psutil。 它简单易用,能提供相当全面的系统信息。

如何用Python监控服务器资源?psutil获取CPU内存使用率

安装psutil非常简单:pip install psutil

如何用Python监控服务器资源?psutil获取CPU内存使用率
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核心的使用率。

如何用Python监控服务器资源?psutil获取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()遍历所有进程,然后根据进程名或其他属性来筛选。

如何将监控数据可视化?

单纯的打印数据可能不够直观,将监控数据可视化可以更方便地发现问题。 可以使用matplotlibplotly等库来绘制图表。 例如,可以创建一个简单的折线图,显示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和内存使用率的折线图。 记得安装matplotlibpip 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.comyour_passwordrecipient_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,内存使用率的知识点!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>