Files
sshclient/core/monitor.py
T
Hermes a57dbc0252 feat: SSHClient v1.0.0 - PyQt5 + paramiko 跨平台 SSH 客户端
功能:
- 多主机管理 (增删改查, 密码/私钥双认证, 导入导出)
- 远程终端 (命令执行 + 常用命令快捷栏 + 超时控制)
- SFTP 文件浏览 (上传/下载带进度, 新建/删除/重命名)
- 实时监控 (CPU/内存/磁盘/网络, 1-10秒可调刷新)
- AI Agent (OpenAI 兼容 API, 5 工具自动调用: 命令/指标/列文件/读文件/上传)

技术栈: PyQt5 + paramiko + psutil + requests + PyInstaller
打包: build_windows.bat / build.sh 一键产出 ~57MB 单文件 exe
测试: core 6/6 + UI 3/3 + E2E 6/6 全部通过
2026-07-28 21:01:31 +08:00

165 lines
6.1 KiB
Python

"""
远程主机系统监控模块
通过 SSH 一次性采集 CPU/内存/磁盘/网络/负载指标。
Linux 用 /proc 和常用命令;macOS/BSD 走兼容路径。
"""
import re
import time
from typing import Optional
from .ssh_client import SSHConnection
class SystemMonitor:
"""远程主机的资源监控器(数据全部从 SSH 通道采集,不依赖 agent)"""
# 一次性获取所有指标的脚本(Linux)
_LINUX_METRICS_SCRIPT = r"""
echo "===CPU==="
# 第一次采样 1 秒间隔,用来计算差值
read cpu_user cpu_nice cpu_system cpu_idle cpu_iowait cpu_irq cpu_softirq cpu_steal < /proc/stat
sleep 1
read cpu_user2 cpu_nice2 cpu_system2 cpu_idle2 cpu_iowait2 cpu_irq2 cpu_softirq2 cpu_steal2 < /proc/stat
total1=$((cpu_user+cpu_nice+cpu_system+cpu_idle+cpu_iowait+cpu_irq+cpu_softirq+cpu_steal))
total2=$((cpu_user2+cpu_nice2+cpu_system2+cpu_idle2+cpu_iowait2+cpu_irq2+cpu_softirq2+cpu_steal2))
idle1=$cpu_idle; idle2=$cpu_idle2
dt=$((total2-total1)); di=$((idle2-idle1))
if [ $dt -gt 0 ]; then usage=$(( (1000*(dt-di)/dt+5)/10 )); else usage=0; fi
echo "CPU_USAGE=$usage"
echo "CPU_CORES=$(nproc 2>/dev/null || echo 1)"
echo "LOAD=$(cat /proc/loadavg | awk '{print $1,$2,$3}')"
echo "UPTIME=$(awk '{printf "%.0f",$1}' /proc/uptime)"
echo "===MEM==="
mem_total=$(awk '/MemTotal/{print $2}' /proc/meminfo)
mem_avail=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
swap_total=$(awk '/SwapTotal/{print $2}' /proc/meminfo)
swap_free=$(awk '/SwapFree/{print $2}' /proc/meminfo)
if [ -z "$mem_avail" ]; then mem_avail=$((mem_total - $(awk '/^(Buffers|Cached|SReclaimable):/{s+=$2} END{print s}' /proc/meminfo))); fi
used=$((mem_total - mem_avail))
echo "MEM_TOTAL=$mem_total"
echo "MEM_USED=$used"
echo "MEM_AVAIL=$mem_avail"
echo "SWAP_TOTAL=$swap_total"
echo "SWAP_USED=$((swap_total-swap_free))"
echo "===DISK==="
df -PB1 -x tmpfs -x devtmpfs 2>/dev/null | awk 'NR>1 {printf "DISK|%s|%d|%d|%s\n",$NF,$2,$3,$5}'
echo "===NET==="
for iface in $(ls /sys/class/net/ 2>/dev/null | grep -v lo); do
rx=$(cat /sys/class/net/$iface/statistics/rx_bytes 2>/dev/null || echo 0)
tx=$(cat /sys/class/net/$iface/statistics/tx_bytes 2>/dev/null || echo 0)
echo "NET|$iface|$rx|$tx"
done
echo "===HOST==="
echo "HOSTNAME=$(hostname)"
echo "KERNEL=$(uname -r)"
echo "OS=$(. /etc/os-release 2>/dev/null && echo "$PRETTY_NAME" || uname -s)"
"""
@staticmethod
def _parse_kv(text: str, key: str, default: str = "0") -> str:
"""从 KEY=VALUE 行中取值"""
m = re.search(rf"^{re.escape(key)}=(.+)$", text, re.MULTILINE)
return m.group(1).strip() if m else default
@classmethod
def collect(cls, conn: SSHConnection) -> dict:
"""采集一次指标;返回 dict"""
empty = {
"cpu": 0.0, "cores": 1, "load1": 0, "load5": 0, "load15": 0,
"uptime": 0, "hostname": "", "kernel": "", "os": "",
"mem_total": 0, "mem_used": 0, "mem_percent": 0.0,
"swap_total": 0, "swap_used": 0,
"disks": [], "net": [],
"ts": time.time(),
}
if not conn or not conn.connected:
return empty
code, out, err = conn.exec_command(cls._LINUX_METRICS_SCRIPT, timeout=10)
if code != 0 or not out:
empty["error"] = err or "采集失败"
return empty
result = dict(empty)
result["hostname"] = cls._parse_kv(out, "HOSTNAME")
result["kernel"] = cls._parse_kv(out, "KERNEL")
result["os"] = cls._parse_kv(out, "OS")
try:
result["cpu"] = float(cls._parse_kv(out, "CPU_USAGE"))
except ValueError:
pass
try:
result["cores"] = int(cls._parse_kv(out, "CPU_CORES", "1"))
except ValueError:
pass
load = cls._parse_kv(out, "LOAD", "0 0 0").split()
try:
result["load1"] = float(load[0])
result["load5"] = float(load[1]) if len(load) > 1 else 0
result["load15"] = float(load[2]) if len(load) > 2 else 0
except (ValueError, IndexError):
pass
try:
result["uptime"] = int(cls._parse_kv(out, "UPTIME"))
except ValueError:
pass
try:
mt = int(cls._parse_kv(out, "MEM_TOTAL"))
mu = int(cls._parse_kv(out, "MEM_USED"))
result["mem_total"] = mt
result["mem_used"] = mu
result["mem_percent"] = (mu / mt * 100) if mt > 0 else 0.0
result["swap_total"] = int(cls._parse_kv(out, "SWAP_TOTAL"))
result["swap_used"] = int(cls._parse_kv(out, "SWAP_USED"))
except ValueError:
pass
result["disks"] = []
for line in out.splitlines():
if line.startswith("DISK|"):
_, mount, total, used, percent = line.split("|", 4)
try:
result["disks"].append({
"mount": mount, "total": int(total),
"used": int(used), "percent": int(percent.rstrip("%")),
})
except ValueError:
continue
result["net"] = []
for line in out.splitlines():
if line.startswith("NET|"):
_, name, rx, tx = line.split("|", 3)
try:
result["net"].append({
"iface": name, "rx": int(rx), "tx": int(tx),
})
except ValueError:
continue
return result
@staticmethod
def format_bytes(n: int) -> str:
"""人类可读字节数"""
n = float(n)
for unit in ("B", "KB", "MB", "GB", "TB", "PB"):
if n < 1024:
return f"{n:.1f}{unit}"
n /= 1024
return f"{n:.1f}EB"
@staticmethod
def format_uptime(seconds: int) -> str:
seconds = int(seconds)
d, rem = divmod(seconds, 86400)
h, rem = divmod(rem, 3600)
m, s = divmod(rem, 60)
if d:
return f"{d}{h}小时"
if h:
return f"{h}小时{m}"
if m:
return f"{m}{s}"
return f"{s}"