Python 脚本实现服务器资源监控
概述
在运维工作中,实时掌握服务器的 CPU、内存、网络及磁盘使用情况至关重要。本文介绍如何在 CentOS Docker 容器中部署 Python 脚本,利用 psutil 和 rich 库实现轻量级的资源监控。通过命令行输出美观的表格数据,便于快速诊断系统状态。
环境准备
Docker 容器搭建
为了隔离运行环境并方便管理,建议将监控脚本运行在独立的 Docker 容器中。以下示例基于 CentOS 镜像:
docker run -it --name monitor-container centos:7 /bin/bash
安全提示:虽然为了方便调试可能会暴露 SSH 端口(如 22 端口),但在生产环境中应谨慎配置防火墙规则,避免不必要的端口暴露风险。
Python 环境安装
CentOS 基础镜像通常不包含 Python 3,需要手动编译安装。这里以 Python 3.9.2 为例:
- 下载源码包:
wget https://registry.npmmirror.com/-/binary/python/3.9.2/Python-3.9.2.tgz
tar -zxvf Python-3.9.2.tgz
cd Python-3.9.2
- 安装编译依赖:
yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make libffi-devel
- 编译安装:
./configure
make && make install
- 验证安装:
which python3 && python3 --version
依赖库配置
为了避免 pip 下载速度过慢,建议配置国内镜像源(如清华大学镜像):
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
安装监控所需的第三方库:
pip3 install psutil rich
脚本实现
核心逻辑
脚本主要使用 psutil 获取系统底层信息,并使用 rich 库美化终端输出。功能涵盖:
- CPU 使用率、频率、核心数
- 内存总量、已用量及使用百分比
- 网络发送与接收字节数
- 磁盘分区使用率
代码详解
创建文件 monitor.py,内容如下:
# -*- encoding: utf-8 -*-
__date__ = '2023/11/02 19:01:26'
import psutil
from rich.table Table
rich.console Console
table = Table(show_header=, header_style=, expand=)
table.add_column(, style=, width=)
table.add_column(, justify=)
cpu_percent = psutil.cpu_percent(interval=)
cpu_freq = psutil.cpu_freq()
cpu_cores = psutil.cpu_count(logical=)
memory = psutil.virtual_memory()
network_stats = psutil.net_io_counters()
disk_stats = psutil.disk_partitions(=)
table.add_row(, )
cpu_freq :
table.add_row(, )
:
table.add_row(, )
table.add_row(, )
table.add_row(, )
table.add_row(, )
table.add_row(, )
table.add_row(, )
table.add_row(, )
partition disk_stats:
:
disk_usage = psutil.disk_usage(partition.mountpoint)
table.add_row(, )
PermissionError:
console = Console()
console.(table)


