aicheckv2-api/utils/ps_util.py
2025-04-11 08:54:28 +08:00

78 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import psutil
import platform
import json
from datetime import datetime
def get_server_info():
# 获取服务器运行状态
info = {}
# 1. 系统基本信息
info["system"] = {
"os": platform.system(),
"os_version": platform.version(),
"node": platform.node(),
"machine": platform.machine(),
"processor": platform.processor(),# 处理器型号
"boot_time": datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") # 启动时间
}
# 2. CPU 信息
cpu_usage = psutil.cpu_percent(interval=1)
info["cpu"] = {
"cpu_count": psutil.cpu_count(logical=False),
"cpu_count_logical": psutil.cpu_count(logical=True),
"cpu_usage": cpu_usage,
"cpu_percent": psutil.cpu_percent(interval=1, percpu=True)
}
# 3. 内存信息
mem = psutil.virtual_memory()
info["memory"] = {
"total": round(mem.total / (1024**3), 2),
"available": round(mem.available / (1024**3), 2),
"percent": mem.percent
}
# 4. 磁盘信息
disks = []
for partition in psutil.disk_partitions():
usage = psutil.disk_usage(partition.mountpoint)
disks.append({
"device": partition.device,
"mountpoint": partition.mountpoint,
"fstype": partition.fstype,
"total": round(usage.total / (1024**3), 2),
"used": round(usage.used / (1024**3), 2),
"percent": usage.percent
})
info["disks"] = disks
# 5. 网络信息
net = psutil.net_io_counters()
info["network"] = {
"bytes_sent": round(net.bytes_sent / (1024**2), 2),
"bytes_recv": round(net.bytes_recv / (1024**2), 2)
}
# 6. 进程信息示例前5个高CPU进程
processes = []
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']):
if len(processes) >= 5:
break
if proc.info['cpu_percent'] > 0:
processes.append({
"PID": proc.info['pid'],
"name": proc.info['name'],
"cpu_percent": proc.info['cpu_percent']
})
info["top_processes"] = sorted(processes, key=lambda x: x["cpu_percent"], reverse=True)
return info
def get_server_json():
server_info = get_server_info()
return json.dumps(server_info, indent=2, ensure_ascii=False)