Python实战:监控VPS服务器硬件温度与内存使用率
想实时掌握VPS服务器的运行状态吗?就像给服务器做“健康体检”,监控硬件温度和内存使用率能帮你提前发现异常——高温可能损坏硬件,内存过载会拖慢服务甚至导致崩溃。本文通过Python实战,教你用几行代码实现VPS服务器的硬件状态监控。

准备工作:安装必要工具
开始前需要做些简单准备。首先确保VPS服务器已安装Python环境(一般Linux系统默认安装Python 3.x),然后需要一个关键工具——psutil(Python系统和进程实用工具库),它能轻松获取CPU、内存等硬件信息。安装方法很简单,在终端输入命令:
pip install psutil
监控硬件温度:给CPU量体温
不同操作系统获取温度的方式不同,这里以常见的Linux VPS服务器为例。我们通过psutil的`sensors_temperatures()`函数读取传感器数据。需要注意,部分VPS可能因虚拟化技术或硬件限制无法获取温度(比如某些云服务商的轻量实例),这时候程序会提示“无法获取CPU温度信息”。以下是示例代码:
import psutil
def get_cpu_temperature():
try:
temps = psutil.sensors_temperatures() # 获取传感器温度数据
if 'coretemp' in temps: # 检查是否存在coretemp传感器(常见于Intel CPU)
core_temps = temps['coretemp']
for entry in core_temps:
print(f"核心 {entry.label}: {entry.current}°C") # 打印每个核心的当前温度
except (AttributeError, KeyError, OSError):
print("无法获取CPU温度信息。")
if __name__ == "__main__":
get_cpu_temperature()
运行这段代码,若VPS支持温度读取,会输出类似“核心 Package id 0: 55°C”的结果。
监控内存使用率:看内存是否超载
内存是VPS服务器处理任务的“临时仓库”,使用率过高会导致程序响应变慢甚至崩溃。用psutil的`virtual_memory()`函数能快速获取内存数据。代码中我们将总内存和已用内存转换为GB(1GB=1024³字节),并计算使用率百分比。示例代码:
import psutil
def get_memory_usage():
memory = psutil.virtual_memory() # 获取内存信息
total = memory.total / (1024 ** 3) # 总内存(GB)
used = memory.used / (1024 ** 3) # 已用内存(GB)
percent = memory.percent # 使用率百分比
print(f"总内存: {total:.2f} GB")
print(f"已使用内存: {used:.2f} GB")
print(f"内存使用率: {percent}%")
if __name__ == "__main__":
get_memory_usage()
假设输出“总内存: 7.79 GB,已使用内存: 4.21 GB,内存使用率: 54.0%”,说明当前内存使用较合理。
定时监控:让脚本自动“巡逻”
为了持续观察状态,我们可以让程序定时运行。这里用`while True`循环实现“无限任务”,每次执行完监控后通过`time.sleep(60)`暂停60秒(可根据需求调整间隔,比如30秒或5分钟)。需要注意长期运行时,建议将脚本放入后台(如用`nohup python script.py &`命令),避免终端关闭导致程序停止。示例代码:
import psutil
import time
def get_cpu_temperature():
try:
temps = psutil.sensors_temperatures()
if 'coretemp' in temps:
core_temps = temps['coretemp']
for entry in core_temps:
print(f"核心 {entry.label}: {entry.current}°C")
except (AttributeError, KeyError, OSError):
print("无法获取CPU温度信息。")
def get_memory_usage():
memory = psutil.virtual_memory()
total = memory.total / (1024 ** 3)
used = memory.used / (1024 ** 3)
percent = memory.percent
print(f"总内存: {total:.2f} GB")
print(f"已使用内存: {used:.2f} GB")
print(f"内存使用率: {percent}%")
if __name__ == "__main__":
while True:
print("\n=== 开始监控VPS服务器状态 ===")
get_cpu_temperature()
get_memory_usage()
print("=== 监控完成,60秒后重试 ===")
time.sleep(60) # 可修改为30(30秒)或300(5分钟)
通过这些Python脚本,你能轻松实现VPS服务器的硬件温度和内存监控。实际使用中可以结合报警功能(比如温度超80℃发邮件通知),进一步提升运维效率。现在就动手试试,让你的VPS服务器始终保持“健康状态”吧!