Files
aicheckv2/app/util/ps_util.py

79 lines
2.4 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版本": platform.version(),
"主机名": platform.node(),
"架构": platform.machine(),
"处理器型号": platform.processor(),
"启动时间": datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
}
# 2. CPU 信息
cpu_usage = psutil.cpu_percent(interval=1)
info["cpu"] = {
"物理核心数": psutil.cpu_count(logical=False),
"逻辑核心数": psutil.cpu_count(logical=True),
"当前使用率 (%)": cpu_usage,
"每个核心使用率": psutil.cpu_percent(interval=1, percpu=True)
}
# 3. 内存信息
mem = psutil.virtual_memory()
info["memory"] = {
"总内存 (GB)": round(mem.total / (1024**3), 2),
"可用内存 (GB)": round(mem.available / (1024**3), 2),
"使用率 (%)": mem.percent
}
# 4. 磁盘信息
disks = []
for partition in psutil.disk_partitions():
usage = psutil.disk_usage(partition.mountpoint)
disks.append({
"设备": partition.device,
"挂载点": partition.mountpoint,
"文件系统": partition.fstype,
"总空间 (GB)": round(usage.total / (1024**3), 2),
"已用空间 (GB)": round(usage.used / (1024**3), 2),
"使用率 (%)": usage.percent
})
info["disks"] = disks
# 5. 网络信息
net = psutil.net_io_counters()
info["network"] = {
"发送流量 (MB)": round(net.bytes_sent / (1024**2), 2),
"接收流量 (MB)": 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'],
"进程名": proc.info['name'],
"CPU使用率 (%)": proc.info['cpu_percent']
})
info["top_processes"] = sorted(processes, key=lambda x: x["CPU使用率 (%)"], reverse=True)
return info
def get_server_json():
server_info = get_server_info()
return json.dumps(server_info, indent=2, ensure_ascii=False)