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

雪夜
发布: 2025-07-03 13:44:01
原创
314人浏览过

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和内存的使用率,直到你手动停止它。

立即学习Python免费学习笔记(深入)”;

如何更精确地监控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()遍历所有进程,然后根据进程名或其他属性来筛选。

AppMall应用商店
AppMall应用商店

AI应用商店,提供即时交付、按需付费的人工智能应用服务

AppMall应用商店 56
查看详情 AppMall应用商店

如何将监控数据可视化?

单纯的打印数据可能不够直观,将监控数据可视化可以更方便地发现问题。 可以使用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内存使用率的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号