23 Commits
Author SHA1 Message Date
jinghui bf5a1c7301 更新 README.md 2026-11-06 17:28:30 +08:00
jinghui 6620377934 更新 README.md 2026-11-06 17:25:07 +08:00
jinghui 81df67fb20 更新 README.md 2026-11-06 17:21:11 +08:00
jinghui 96442db19c 上传文件至「docs」 2026-11-06 17:19:26 +08:00
jinghui 0936a86d0e 更新 README.md 2026-11-06 17:18:48 +08:00
jinghui ed23092cd6 feat: rename memory recycle button 2026-11-06 17:16:27 +08:00
jinghui d5e78908fb docs: full-page screenshots 2026-11-06 17:10:57 +08:00
jinghui e0627a9158 docs: add per-page screenshots 2026-11-06 17:08:54 +08:00
jinghui 986dc63179 更新 README.md 2026-11-06 17:02:22 +08:00
jinghui fc764b9faa 更新 README.md 2026-11-06 16:52:04 +08:00
jinghui 44eccf9a75 更新 README.md 2026-11-06 16:43:52 +08:00
jinghui 1abd96f081 v1.2.6 version in top-right 2026-11-06 16:37:59 +08:00
jinghui 37727fa9df feat: add install.sh and docker-compose for auto-update 2026-11-06 16:37:28 +08:00
jinghui c13dfb6df8 v1.2.5 top-right links 2026-11-06 16:30:10 +08:00
jinghui 42f1d20a99 docs: advantage comparison 2026-11-06 16:28:17 +08:00
jinghui 9e2475dfe0 docs: detailed README 2026-11-06 16:27:02 +08:00
jinghui 5d46667aef docs: use public TCR image address 2026-11-06 16:23:47 +08:00
jinghui d1c923d59e docs: add screenshot and details 2026-11-06 16:23:17 +08:00
jinghui 28eecb55ed docs: clean README for fnos-resmon 2026-11-06 16:21:59 +08:00
jinghui 3f72ef7412 feat: add source code 2026-11-06 16:20:25 +08:00
jinghui 843322534f v1.2.4 floating footer 2026-11-06 16:16:46 +08:00
jinghui b52df4b192 v1.2.3 public links 2026-11-06 16:14:34 +08:00
jinghui f49315dd23 v1.2.2 2026-11-06 16:13:20 +08:00
15 changed files with 1809 additions and 206 deletions

No files matched your search

+10 -26
View File
@@ -1,27 +1,11 @@
# Use an official Python runtime as a parent image FROM python:3.11-slim
FROM python:3.9-slim-bullseye
# Set the working directory in the container
WORKDIR /app WORKDIR /app
RUN pip install --no-cache-dir flask psutil -i https://mirrors.aliyun.com/pypi/simple/
# Install system dependencies (for psutil if needed) COPY app.py .
RUN apt-get update && apt-get install -y \ COPY hw_mem.json .
smartmontools \ COPY hw_disk.json .
net-tools \ COPY hw_net.json .
iproute2 \ COPY public ./public
procps \ ENV PORT=7031
lm-sensors \ EXPOSE 7031
--no-install-recommends && \ CMD ["python", "app.py"]
rm -rf /var/lib/apt/lists/*
# Copy the current directory contents into the container at /app
COPY . /app
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Make port 5000 available to the world outside this container
EXPOSE 5000
# Run app.py when the container launches
CMD ["python3", "app.py"]
+64 -175
View File
@@ -1,78 +1,78 @@
<div align="center"> # 飞牛NAS必装:进程级资源监控,比自带强10倍,一眼看穿谁在偷吃你的CPU/内存/磁盘/网络全透视,带一键内存回收的监控面板
CPU/内存/磁盘/网络 + 进程排行 + 一键回收 + SMART/连接明细,Docker一键部署
# 🖥️ 小白系统监控器 — fnOS飞牛实时系统监控面板 - docker应用 > 飞牛 NAS 专属的轻量级系统资源监控面板 —— 一个 Docker 命令即可拥有媲美专业 NAS 监控的 Web 界面。
**一键 Docker 部署 | 6 大监控维度 | 数据可导出**
[![Docker Hub](https://img.shields.io/badge/Docker-Hub-2496ED?style=flat&logo=docker)](https://hub.docker.com/r/jinghui1984/fnmon)
[![GitHub stars](https://img.shields.io/github/stars/personal82555/fnmon?style=social)](https://github.com/personal82555/fnmon)
[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
[![fnOS](https://img.shields.io/badge/fnOS-%E9%A3%9E%E7%89%9B-orange)](https://www.fnnas.com)
--- ---
<p align="center"> ## ✨ 为什么选择 fnos-resmon?与飞牛自带的对比
<img src="https://img.88531.cn/i/2026/06/15/6a2ed1dd6dbc5.png" alt="fnmon 总览" width="80%"/>
</p>
**fnmon** 是一款专为飞牛 fnOS 打造的实时系统监控面板。一个 Docker 命令即可拥有媲美专业 NAS 监控的 Web 界面,涵盖 **CPU、内存、网络、磁盘、进程排行、应用用量** 六大维度,所有历史数据支持一键导出。 飞牛自带的系统信息只能看到 CPU/内存占用率、存储卷用量等**汇总数字**:哪个进程在吃 CPU?哪块盘 SMART 告警了?哪个端口被谁占用了?一键能回收内存吗?这些它都做不到。fnos-resmon 正好补上这些短板:
</div> | 能力 | 飞牛自带 | fnos-resmon |
|------|---------|-------------|
| CPU/内存占用率 | ✅ 有 | ✅ 有 |
| 进程级 CPU/内存排行 | ❌ 无 | ✅ 进程名/PID/用户/状态/线程数 |
| 内存 RSS/USS/SWAP 明细 | ❌ 无 | ✅ 三列细分 |
| 一键内存回收(drop caches) | ❌ 无 | ✅ 一键释放 |
| 一键结束异常进程 | ❌ 无 | ✅ 一键 kill |
| 磁盘 SMART/温度/通电时间 | ❌ 需命令行 | ✅ Web 直观展示 |
| TCP 连接明细/侦听端口 | ❌ 无 | ✅ 进程+地址+状态 |
| 网卡驱动/MTU/双工 | ❌ 无 | ✅ 有 |
| 表头排序/箭头指示 | ❌ 无 | ✅ 点击即排序 |
--- - 🚀 **一键部署**:一条 `docker run` 启动,无需额外驱动
- ⚡ **实时刷新**:3 秒自动更新,数据实时
## ✨ 核心特性 - 📊 **维度全面**:CPU / 内存 / 磁盘 / 网络 四大面板,进程级明细
- 🔍 **进程级洞察**:每个进程 CPU、内存、IO、连接数一目了然
| 特性 | 说明 | - 🧹 **内存回收**:一键 drop caches 释放可回收内存
|------|------| - 🔪 **进程管理**:一键结束异常进程
| 🚀 **一键部署** | 一条 `docker run` 命令启动,无需安装驱动 | - 📱 **移动适配**:响应式布局,手机也能看
| ⚡ **实时推送** | SSE 技术,2 秒刷新一次,延迟极低 | - 🐳 **零侵入**:Docker 容器运行,不修改系统文件
| 📊 **维度全面** | 6 大面板覆盖系统全部关键指标 |
| 💾 **数据导出** | 一键导出所有历史数据到 NAS 目录,JSON 格式 |
| 📱 **移动适配** | 深色主题,侧边栏导航,屏幕利用率高 |
| 🐳 **零侵入** | Docker 容器运行,不修改系统文件 |
--- ---
## 📸 功能截图 ## 📸 功能截图
### ⚡ CPU 监控 ![CPU](docs/PixPin_2026-11-06_17-13-43.png)
实时显示 CPU 型号、每个核心的当前频率、Governor/EPP 运行模式、核心温度(支持 SATA/NVMe 硬盘温度)、Turbo Boost 状态、60 秒频率历史曲线图。还包括 CPU 评测跑分(PassMark/Cinebench/Geekbench)和同级 CPU 横向对比。
<p align="center"> ![内存](docs/mem.png)
<img src="https://img.88531.cn/i/2026/06/15/6a2ed1db91017.png" alt="CPU 面板" width="90%"/>
</p>
### 🧠 内存监控 ![磁盘](docs/disk.png)
总容量 / 已用 / 可用 / 缓存 / SWAP 全面展示,进度条可视化,数据实时更新。
<p align="center"> ![网络](docs/net.png)
<img src="https://img.88531.cn/i/2026/06/15/6a2ed1dcc7cc3.png" alt="内存面板" width="90%"/>
</p>
### 🌐 网络流量 ---
实时上传/下载网速、当月/当日累计流量、Docker 容器流量排行(TOP 15)、60 秒流量趋势图。
<p align="center"> ## 📋 功能清单
<img src="https://img.88531.cn/i/2026/06/15/6a2ed1dc13916.png" alt="网络面板" width="90%"/>
</p>
### 💾 磁盘健康 ### CPU 监控
物理硬盘列表(型号、容量、接口类型)、SMART 健康状态、硬盘温度、NVMe 寿命百分比、通电时间、总写入量。磁盘分区挂载点使用率 + 60 秒 I/O 趋势图。 - CPU 型号、架构、物理/逻辑核数
- 实时 CPU 占用率、负载(1/5/15 分钟)
- 每核心频率与占用率可视化
- L1/L2/L3 缓存信息
- 进程 CPU 占用排行(TOP N)
<p align="center"> ### 内存监控
<img src="https://img.88531.cn/i/2026/06/15/6a2ed1de2fcce.png" alt="磁盘面板" width="90%"/> - 内存占用率、已用/总共/可用
</p> - SWAP 使用情况
- 物理内存槽位详情(容量、类型、频率、厂商)
- 进程 RSS / USS / SWAP 明细
- 一键回收可回收内存(drop caches)
### 📱 应用用量排行 ### 磁盘监控
综合 CPU + 内存 + 网络 三维度加权评分,可按 **日/周/月/年/总计** 切换时间维度,快速定位资源消耗大户。 - 挂载点使用率、读写累计
- 物理硬盘 SMART 健康状态
- 硬盘温度、通电时间、坏道重映射
- 阵列拓扑展示
<p align="center"> ### 网络监控
<img src="https://img.88531.cn/i/2026/06/15/6a2ed1df0cf82.png" alt="应用用量排行" width="90%"/> - 实时上传/下载速率、累计收发量
</p> - 连接数统计
- TCP 连接明细表(进程、本地/远程地址、状态)
### 🔝 进程 CPU 排名 - 侦听端口表
实时 TOP 20 进程,含 PID、用户、CPU%、内存%、启动时间。CPU% 用颜色标识(🔴>50% / 🟠>20% / 🟡>5%)。 - 网卡信息(IP、MAC、速率、双工、MTU、驱动)
--- ---
@@ -81,62 +81,13 @@
### 方式一:Docker 运行(推荐) ### 方式一:Docker 运行(推荐)
```bash ```bash
docker run -d --name fnmon -p 5000:5000 --privileged \ docker run -d --name fnos-resmon -p 7031:7031 --privileged \
-v /proc:/proc:ro -v /sys:/sys:ro \ -v /proc:/host/proc:rw -v /sys:/host/sys:ro \
-v /vol2/fnmon-exports:/var/exports \ jpccr.ccs.tencentyun.com/jinghui/fnos-resmon:latest
jinghui1984/fnmon
``` ```
启动后浏览器访问 `http://你的NASIP:5000` 即可。 启动后浏览器访问 `http://你的NASIP:7031` 即可。
> **📌 导出目录说明:** `-v /vol2/fnmon-exports:/var/exports` 用于保存导出的历史数据,如不需要可省略。
### 方式二:Docker Compose
```yaml
version: '3'
services:
fnmon:
image: jinghui1984/fnmon
container_name: fnmon
restart: always
ports:
- "5000:5000"
privileged: true
volumes:
- /proc:/proc:ro
- /sys:/sys:ro
- /vol2/fnmon-exports:/var/exports
environment:
- TZ=Asia/Shanghai
```
---
## 🔧 功能详解
### 数据导出
点击侧边栏底部的 **⬇️ 导出** 按钮,一键将所有历史数据保存为 JSON 文件到挂载的 NAS 目录。文件名格式:`fnmon-export-YYYY-MM-DD-HHMMSS.json`。
导出的数据包含:
| 内容 | 说明 |
|------|------|
| CPU 实时数据 | 频率、温度、Governor、EPP |
| 内存快照 | 已用、缓存、SWAP |
| 网络历史 | 60 秒流量队列 |
| 磁盘 I/O | 设备读写速率 |
| 应用用量 | SQLite 全量数据(日/周/月/年 聚合) |
| Docker 流量 | 容器网络存档 |
通过 ⚙️ **设置** 按钮可自由配置导出路径。
### 历史数据追踪
- **网络流量**:累计统计总/日/月 流量,Docker 容器排行
- **应用用量**:60 秒采集一次进程 + Docker 资源快照,自动聚合到日/周/月/年维度
- **SSE 实时推送**:2 秒间隔推送所有数据,前端自动渲染
--- ---
@@ -146,29 +97,8 @@ services:
|------|---------| |------|---------|
| 后端框架 | Flask (Python) | | 后端框架 | Flask (Python) |
| 前端 | 纯 HTML/CSS/JS(无额外依赖) | | 前端 | 纯 HTML/CSS/JS(无额外依赖) |
| 实时通信 | Server-Sent Events (SSE) |
| 数据采集 | psutil、smartctl、/proc 文件系统 | | 数据采集 | psutil、smartctl、/proc 文件系统 |
| 数据存储 | SQLite(应用用量 + 流量审计) | | 容器化 | Docker |
| 容器化 | Docker(基于 python:3.9-slim) |
| 镜像大小 | ~342MB |
---
## 📋 功能清单
- [x] CPU 频率 / 核心温度 / Governor / EPP
- [x] 内存 / SWAP 实时 & 趋势
- [x] 网络流量实时 & 累计(日 / 月 / 总)
- [x] Docker 容器流量排行
- [x] 磁盘分区使用率 & I/O 趋势
- [x] 物理硬盘健康(SMART / NVMe 寿命)
- [x] 进程 CPU 占用排行(TOP 20)
- [x] 应用用量排行(日/周/月/年)
- [x] CPU 评测跑分 & 同级对比
- [x] 一键数据导出
- [ ] 暗色 / 亮色主题切换
- [ ] 微信 / 邮件告警
- [ ] 多语言支持
--- ---
@@ -176,55 +106,14 @@ services:
| 资源 | 地址 | | 资源 | 地址 |
|------|------| |------|------|
| Docker Hub | `jinghui1984/fnmon` | | Docker 镜像 | `jpccr.ccs.tencentyun.com/jinghui/fnos-resmon:latest` |
| GitHub | 本仓库 | | Gitea 仓库 | https://gitea.88531.cn/jinghui/fnos-resmon |
| 论坛讨论 | [飞牛论坛](https://club.fnnas.com) |
欢迎 Issue 和 PR!
--- ---
## 🤝 贡献 ## 🔗 链接
欢迎 Issue 和 PR!如果你有好的想法或发现了 Bug,请到 [Issues](https://github.com/personal82555/fnmon/issues) 提出。
---
<div align="center">
---
## 📦 安装步骤
1. 下载 FPK:[fnos-resmon-v1.2.1.fpk](http://192.168.68.19:3200/attachments/61f85108-f698-4682-a273-8f9b6ebc7fac)
2. 飞牛应用中心 → 本地安装 → 选择 FPK
3. 安装完成后打开「飞牛资源管理器」,访问 `http://<NAS IP>:7031`
或直接拉取镜像:
```bash
docker pull 192.168.68.19:3200/jinghui/fnos-resmon:latest
```
## fnos-resmon(飞牛资源管理器)
本仓库另含 fnos-resmon:CPU / 内存 / 磁盘 / 网络 四页签资源监视器,读取宿主真实数据。
### 功能
- CPU:进程 CPU 占用、线程数、PID、描述、用户、状态,可按列排序
- 内存:RSS / USS / SWAP 三列
- 磁盘:进程读写累计
- 网络:连接数进程、TCP 连接表、侦听端口表
- 内存回收:一键 drop caches
- 进程结束:一键 kill
- 表头排序方向可视化,内部滚动自适应
### 下载
- FPK:`/vol2/1000/HD2/fpk/fnos-resmon-v1.2.0.fpk`
- 镜像:`192.168.68.19:3200/jinghui/fnos-resmon:latest`
### 链接
- 资享导航站:https://nav.88531.cn - 资享导航站:https://nav.88531.cn
- 开源地址:http://192.168.68.19:3200/jinghui/fnos-resmon - 开源地址:https://gitea.88531.cn/jinghui/fnos-resmon
</div>
+827
View File
@@ -0,0 +1,827 @@
from flask import Flask, jsonify, request, send_from_directory
import psutil, os, time, signal, threading, subprocess, platform, glob, json, struct
try:
psutil.PROCFS_PATH = os.environ.get("PROCFS_PATH", "/proc")
except Exception:
pass
PROCFS = os.environ.get("PROCFS_PATH", "/host/proc")
if os.path.isdir(PROCFS):
psutil.PROCFS_PATH = PROCFS
app = Flask(__name__, static_folder="public", static_url_path="")
PORT = int(os.environ.get("PORT", "7031"))
# ---------- background sampler ----------
cache = {"procs": [], "cpu": 0.0, "load": [0, 0, 0], "ts": 0}
net_prev = {}
net_rate = {}
def fmt_status(s):
m = {
psutil.STATUS_RUNNING: ("活动", 1),
psutil.STATUS_SLEEPING: ("睡眠", 0),
psutil.STATUS_DISK_SLEEP: ("睡眠", 0),
psutil.STATUS_STOPPED: ("停止", 0),
psutil.STATUS_ZOMBIE: ("僵尸", 0),
}
return m.get(s, ("睡眠", 0))
_uid_cache = {"map": {}, "ts": 0}
def uid_name(uid_str):
# 容器内 /etc/passwd 没有宿主用户,uid 会显示成数字,用宿主 passwd 还原
if not uid_str or not uid_str.isdigit():
return uid_str
now = time.time()
if now - _uid_cache["ts"] > 300:
m = {}
try:
with open("/host/etc/passwd") as f:
for line in f:
p = line.split(":")
if len(p) > 3:
try:
m[p[2]] = p[0]
except Exception:
pass
except Exception:
pass
_uid_cache["map"] = m
_uid_cache["ts"] = now
return _uid_cache["map"].get(uid_str, uid_str)
def sample_procs():
# init cpu percent calculation
for p in psutil.process_iter():
try:
p.cpu_percent(None)
except Exception:
pass
time.sleep(1.0)
procs = []
try:
cpu_total = psutil.cpu_percent(interval=None)
except Exception:
cpu_total = 0
try:
load = list(os.getloadavg())
except Exception:
load = [0, 0, 0]
for p in psutil.process_iter(["pid", "name", "username", "status", "num_threads", "cmdline"]):
try:
with p.oneshot():
cpu = p.cpu_percent(None)
mem = p.memory_percent()
try:
rss = p.memory_info().rss
except Exception:
rss = 0
uss = 0
swap = 0
try:
mfi = p.memory_full_info()
uss = getattr(mfi, "uss", 0) or 0
swap = getattr(mfi, "swap", 0) or 0
except Exception:
pass
try:
io = p.io_counters()
rd, wr = io.read_bytes, io.write_bytes
except Exception:
rd, wr = 0, 0
try:
conns = len(p.net_connections())
except Exception:
conns = 0
info = p.info
name = info.get("name") or ""
cmd = " ".join(info.get("cmdline") or [])[:120]
desc = cmd if cmd else name
st, act = fmt_status(info.get("status"))
if (not act) and (cpu or 0) > 1.0:
st, act = "活动", 1
procs.append({
"name": name[:40], "pid": info["pid"],
"cpu": round(cpu or 0, 2), "mem": round(mem or 0, 2),
"rss": rss, "uss": uss, "swap": swap, "threads": info.get("num_threads") or 0,
"user": uid_name(str(info.get("username") or ""))[:20],
"status": st, "active": act,
"desc": desc[:80], "io_r": rd, "io_w": wr, "conns": conns,
})
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
except Exception:
continue
procs.sort(key=lambda x: x["cpu"], reverse=True)
cache["procs"] = procs
cache["cpu"] = round(cpu_total, 1)
cache["load"] = [round(x, 2) for x in load]
cache["ts"] = time.time()
def sampler_loop():
while True:
try:
sample_procs()
except Exception:
pass
time.sleep(2)
threading.Thread(target=sampler_loop, daemon=True).start()
# warm up immediately in background; serve stale until ready
@app.route("/")
def index():
return send_from_directory("public", "index.html")
@app.route("/api/cpu")
def api_cpu():
active = sum(1 for p in cache["procs"] if p["active"])
return jsonify({"cpu": cache["cpu"], "load": cache["load"],
"active": active, "total": len(cache["procs"]),
"info": get_cpu_info(), "percpu": get_percpu(),
"items": cache["procs"][:100]})
_cpu_static = {}
def _parse_host_cpuinfo():
info = {}
try:
with open("/host/proc/cpuinfo") as f:
txt = f.read()
except Exception:
try:
with open("/proc/cpuinfo") as f:
txt = f.read()
except Exception:
return info
# 取第一个 processor 段的 model name / cache size / cpu MHz
for line in txt.splitlines():
if ":" not in line:
continue
k, v = line.split(":", 1)
k, v = k.strip(), v.strip()
if k == "model name" and "model" not in info:
info["model"] = v
elif k == "cache size" and "cache" not in info:
info["cache"] = v
return info
def _parse_lscpu():
out = {}
try:
txt = subprocess.run(["lscpu"], capture_output=True, text=True,
timeout=5).stdout
except Exception:
return out
for line in txt.splitlines():
if ":" not in line and ":" not in line:
continue
line = line.replace(":", ":")
k, v = line.split(":", 1)
k, v = k.strip(), v.strip()
out[k] = v
return out
def get_cpu_info():
global _cpu_static
if not _cpu_static:
ci = _parse_host_cpuinfo()
lc = _parse_lscpu()
def pick(*keys):
for k in keys:
if k in lc and lc[k]:
return lc[k]
return ""
# L1d/L1i/L2/L3 键名中英文兼容
l1d = pick("L1d 缓存", "L1d cache")
l1i = pick("L1i 缓存", "L1i cache")
l2 = pick("L2 缓存", "L2 cache")
l3 = pick("L3 缓存", "L3 cache")
_cpu_static = {
"model": ci.get("model") or pick("型号名称", "Model name"),
"arch": platform.machine(),
"sockets": pick("座", "Socket(s)"),
"cores_per_socket": pick("每个座的核数", "Core(s) per socket"),
"threads_per_core": pick("每个核的线程数", "Thread(s) per core"),
"l1d": l1d, "l1i": l1i, "l2": l2, "l3": l3,
"cache": ci.get("cache", ""),
}
try:
f = psutil.cpu_freq()
cur = round(f.current, 0) if f else 0
fmin = round(f.min, 0) if f and f.min else 0
fmax = round(f.max, 0) if f and f.max else 0
except Exception:
cur = fmin = fmax = 0
d = dict(_cpu_static)
d.update({
"logical": psutil.cpu_count() or 0,
"physical": psutil.cpu_count(logical=False) or 0,
"freq_cur": cur, "freq_min": fmin, "freq_max": fmax,
})
return d
def get_percpu():
try:
vals = psutil.cpu_percent(interval=None, percpu=True)
return [round(v, 1) for v in (vals or [])]
except Exception:
return []
@app.route("/api/mem")
def api_mem():
vm = psutil.virtual_memory()
sm = psutil.swap_memory()
items = sorted(cache["procs"], key=lambda x: x["mem"], reverse=True)[:100]
mi = _read_meminfo_host()
dm = get_mem_hw()
return jsonify({
"total": vm.total, "used": vm.used, "available": vm.available,
"percent": vm.percent, "cached": getattr(vm, "cached", 0),
"swap_total": sm.total, "swap_used": sm.used, "swap_percent": sm.percent,
"detail": mi, "hw": dm,
"items": items})
_mem_hw_static = {}
def _read_meminfo_host():
mi = {}
for p in ("/host/proc/meminfo", "/proc/meminfo"):
try:
with open(p) as f:
for line in f:
if ":" not in line:
continue
k, v = line.split(":", 1)
parts = v.strip().split()
if not parts:
continue
try:
num = int(parts[0])
except ValueError:
continue
# 统一转 bytes
if len(parts) > 1 and parts[1] == "kB":
num *= 1024
mi[k.strip()] = num
if mi:
break
except Exception:
continue
return mi
def _walk_dmi(path):
"""yield (type, raw_bytes, strings)"""
try:
with open(path, "rb") as f:
data = f.read()
except Exception:
return
off, n = 0, 0
L = len(data)
while off + 4 <= L and n < 200:
typ, ln = data[off], data[off + 1]
if ln < 4 or off + ln > L:
break
if typ == 127: # end of table
break
s = off + ln
strs = []
ok = True
while s < L:
try:
e = data.index(b"\x00", s)
except ValueError:
ok = False
break
if e == s:
s += 1
break
strs.append(data[s:e].decode("utf-8", "replace").strip())
s = e + 1
if not ok:
break
yield typ, data[off:off + ln], strs
off = s
n += 1
_MEM_TYPE = {0x02: "Unknown", 0x03: "DRAM", 0x12: "DDR", 0x13: "DDR2",
0x14: "DDR2 FB-DIMM", 0x18: "DDR3", 0x19: "FBD2", 0x1A: "DDR4",
0x1B: "LPDDR", 0x1C: "LPDDR2", 0x1D: "LPDDR3", 0x1E: "LPDDR4",
0x1F: "Logical NV", 0x20: "HBM", 0x21: "HBM2", 0x22: "DDR5",
0x23: "LPDDR5", 0x24: "HBM3"}
def _parse_dmi_mem():
dimms, max_cap_kb = [], 0
for dmi_path in ("/host/sys/firmware/dmi/tables/DMI",
"/sys/firmware/dmi/tables/DMI"):
found = False
for typ, raw, strs in _walk_dmi(dmi_path):
found = True
def S(i):
return strs[i - 1] if 1 <= i <= len(strs) else ""
if typ == 16 and len(raw) >= 11:
import struct
(cap,) = struct.unpack_from("<I", raw, 7)
if cap not in (0, 0x80000000):
max_cap_kb = cap # SMBIOS 单位 kB
elif typ == 17 and len(raw) >= 28:
import struct
(size,) = struct.unpack_from("<H", raw, 12)
if size == 0 or size == 0xFFFF:
continue # 空槽
if size & 0x8000:
mb = size & 0x7FFF # bit15=1 时单位 KB→转MB(向上)
size_mb = max(mb // 1024, 1) if mb >= 1024 else 1
size_b = (size & 0x7FFF) * 1024
else:
size_mb = size & 0x7FFF
size_b = size_mb * 1024 * 1024
if size_mb == 0x7FFF:
continue
(speed,) = struct.unpack_from("<H", raw, 20)
cspeed = 0
if len(raw) >= 30:
(cspeed,) = struct.unpack_from("<H", raw, 28)
mtype = raw[18] if len(raw) > 18 else 0
dimms.append({
"locator": S(raw[16]) if len(raw) > 16 else "",
"bank": S(raw[17]) if len(raw) > 17 else "",
"size_b": size_b, "size_mb": size_mb,
"type": _MEM_TYPE.get(mtype, "DDR4" if mtype == 0 else hex(mtype)),
"speed": speed or 0, "cspeed": cspeed or 0,
"maker": S(raw[22]) if len(raw) > 22 else "",
"serial": S(raw[23]) if len(raw) > 23 else "",
"part": S(raw[25]) if len(raw) > 25 else "",
})
if found:
break
return dimms, max_cap_kb
def _get_vram():
total = 0
for base in ("/host/sys/class/drm", "/sys/class/drm"):
try:
for p in glob.glob(base + "/card*/device/mem_info_vram_total"):
try:
with open(p) as f:
total += int(f.read().strip())
except Exception:
pass
except Exception:
pass
if total:
break
return total
def get_mem_hw():
global _mem_hw_static
if not _mem_hw_static:
dimms, max_cap_kb = [], 0
# 优先读构建时从宿主 dmidecode 导出的静态槽位表
for jp in ("hw_mem.json",
os.path.join(os.path.dirname(os.path.abspath(__file__)),
"hw_mem.json")):
try:
with open(jp) as f:
hj = json.load(f)
dimms = hj.get("dimms", []) or []
max_cap_kb = int((hj.get("max_cap_b", 0) or 0) // 1024)
if dimms:
break
except Exception:
continue
if not dimms:
dimms, max_cap_kb = _parse_dmi_mem()
installed = sum(d["size_b"] for d in dimms)
_mem_hw_static = {"dimms": dimms, "installed": installed,
"max_cap_kb": max_cap_kb}
d = {"dimms": _mem_hw_static["dimms"],
"installed": _mem_hw_static["installed"],
"max_cap_kb": _mem_hw_static["max_cap_kb"]}
try:
mem_total = psutil.virtual_memory().total
except Exception:
mem_total = 0
d["vram"] = _get_vram()
d["system_total"] = mem_total
d["reserved"] = (d["installed"] - mem_total) if d["installed"] and mem_total else 0
return d
HOST_MNTS = [("/", "/host"), ("/vol1", "/host/vol1"),
("/vol2", "/host/vol2"), ("/vol3", "/host/vol3")]
def _df_host():
"""容器内 df 直读宿主路径(经 bind 进来的宿主目录),返回 {mnt: {...}}"""
try:
out = subprocess.run(
["df", "-B1", "--output=source,target,fstype,size,used,avail",
"/host", "/host/vol1", "/host/vol2", "/host/vol3"],
capture_output=True, text=True, timeout=5).stdout.splitlines()
res = {}
for line in out[1:]:
p = line.split()
if len(p) < 6:
continue
dev, tgt, fst, size, used, avail = p[0], p[1], p[2], int(p[3]), int(p[4]), int(p[5])
mnt = tgt.replace("/host", "", 1) or "/"
res[mnt] = {"device": dev, "mount": mnt, "fstype": fst,
"total": size, "used": used, "free": avail,
"percent": round(used / size * 100, 1) if size else 0}
return res
except Exception:
return {}
@app.route("/api/mem/drop", methods=["POST"])
def api_mem_drop():
import subprocess
try:
subprocess.run(["sync"], check=False, timeout=10)
p = os.environ.get("PROCFS_PATH", "/proc")
with open(os.path.join(p, "sys", "vm", "drop_caches"), "w") as f:
f.write("3")
vm = psutil.virtual_memory()
return jsonify({"ok": True, "available": vm.available, "percent": vm.percent})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.route("/api/disk")
def api_disk():
parts = []
dfm = _df_host()
for mp, hp in HOST_MNTS:
if mp in dfm:
parts.append(dfm[mp])
continue
try:
st = os.statvfs(hp)
total = st.f_blocks * st.f_frsize
free = st.f_bavail * st.f_frsize
used = total - free
parts.append({"device": "?", "mount": mp, "fstype": "?",
"total": total, "used": used, "free": free,
"percent": round(used / total * 100, 1) if total else 0})
except Exception:
continue
try:
dio = psutil.disk_io_counters()
dio_d = {"read": dio.read_bytes, "write": dio.write_bytes} if dio else {}
except Exception:
dio_d = {}
# top io processes
items = sorted(cache["procs"], key=lambda x: x["io_r"] + x["io_w"], reverse=True)[:60]
return jsonify({"parts": parts, "io": dio_d, "hw": get_disk_hw(),
"items": items})
_disk_hw_static = {}
def _read(p, default=""):
try:
with open(p) as f:
return f.read().strip()
except Exception:
return default
def _sys_block_base():
for base in ("/host/sys/block", "/sys/block"):
try:
if os.path.isdir(base):
return base
except Exception:
continue
return "/host/sys/block"
def _live_sysfs(name):
"""实时 sysfs: 容量/转速/型号(覆盖静态快照中的漂移项)"""
base = _sys_block_base()
d = os.path.join(base, name)
out = {}
try:
sectors = _read(os.path.join(d, "size"))
if sectors.isdigit():
out["cap_b"] = int(sectors) * 512
except Exception:
pass
rot = _read(os.path.join(d, "queue/rotational"))
if rot in ("0", "1"):
out["rotational"] = (rot == "1")
model = _read(os.path.join(d, "device/model"))
if model:
out["sys_model"] = model
vendor = _read(os.path.join(d, "device/vendor"))
if vendor:
out["sys_vendor"] = vendor
return out
def _live_mdstat():
"""实时 mdstat: 每组阵列状态/同步进度,键为 md 名"""
st = {}
for p in ("/host/proc/mdstat", "/proc/mdstat"):
try:
with open(p) as f:
txt = f.read()
break
except Exception:
txt = ""
else:
return st
import re
cur = None
for line in txt.splitlines():
m = re.match(r"^(md\d+)\s*:\s*(\w+)\s+(\w+)(.*)$", line)
if m:
cur = m.group(1)
st[cur] = {"status": m.group(2), "level": m.group(3),
"devs": m.group(4).strip(), "sync": ""}
continue
if cur and ("recovery" in line or "resync" in line or "blocks" in line):
s = line.strip()
if "recovery" in line or "resync" in line:
st[cur]["sync"] = s
elif "blocks" in line and not st[cur].get("blocks"):
st[cur]["blocks"] = s
return st
def _live_perdisk_io():
try:
d = psutil.disk_io_counters(perdisk=True) or {}
except Exception:
return {}
out = {}
for k, v in d.items():
try:
out[k] = {"read": v.read_bytes, "write": v.write_bytes}
except Exception:
continue
return out
def get_disk_hw():
global _disk_hw_static
if not _disk_hw_static:
hj = {}
for jp in ("hw_disk.json",
os.path.join(os.path.dirname(os.path.abspath(__file__)),
"hw_disk.json")):
try:
with open(jp) as f:
hj = json.load(f)
if hj.get("disks"):
break
except Exception:
continue
_disk_hw_static = hj or {"disks": [], "arrays": []}
disks = [dict(x) for x in _disk_hw_static.get("disks", [])]
arrays = [dict(x) for x in _disk_hw_static.get("arrays", [])]
# 合并实时数据
pio = _live_perdisk_io()
for dk in disks:
nm = dk.get("name", "")
dk.update(_live_sysfs(nm))
if nm in pio:
dk["io_read"] = pio[nm]["read"]
dk["io_write"] = pio[nm]["write"]
# 转速文字
if dk.get("rotational") is True and not dk.get("rpm"):
dk["rpm"] = 5400
md_live = _live_mdstat()
for a in arrays:
md = a.get("md", "")
lv = md_live.get(md, {})
if lv:
a["live_status"] = lv.get("status", "")
a["live_devs"] = lv.get("devs", "")
a["live_sync"] = lv.get("sync", "")
if md in pio:
a["io_read"] = pio[md]["read"]
a["io_write"] = pio[md]["write"]
return {"disks": disks, "arrays": arrays,
"extra": _disk_hw_static.get("extra", {}),
"snapshot": _disk_hw_static.get("snapshot", ""),
"note": _disk_hw_static.get("note", "")}
@app.route("/api/net")
def api_net():
global net_prev, net_rate
now = time.time()
try:
counters = psutil.net_io_counters(pernic=True)
except Exception:
counters = {}
rates = []
for nic, c in counters.items():
if nic.startswith(("lo", "docker", "br-", "veth")):
continue
prev = net_prev.get(nic)
if prev:
dt = max(now - prev["t"], 0.5)
up = (c.bytes_sent - prev["sent"]) / dt
down = (c.bytes_recv - prev["recv"]) / dt
else:
up = down = 0
net_prev[nic] = {"sent": c.bytes_sent, "recv": c.bytes_recv, "t": now}
rates.append({"nic": nic, "up": max(up, 0), "down": max(down, 0),
"sent": c.bytes_sent, "recv": c.bytes_recv})
rates.sort(key=lambda x: x["up"] + x["down"], reverse=True)
try:
conns = len(psutil.net_connections())
except Exception:
conns = 0
total_recv = 0
total_sent = 0
for nic, c in counters.items():
if nic.startswith(("lo", "docker", "br-", "veth")):
continue
total_recv += getattr(c, "bytes_recv", 0) or 0
total_sent += getattr(c, "bytes_sent", 0) or 0
items = sorted(cache["procs"], key=lambda x: x["conns"], reverse=True)[:60]
tcp_list = []
listen_list = []
try:
name_by_pid = {p["pid"]: p["name"] for p in cache.get("procs", [])}
for c in psutil.net_connections(kind="tcp"):
laddr = f"{c.laddr.ip}:{c.laddr.port}" if c.laddr else ""
raddr = f"{c.raddr.ip}:{c.raddr.port}" if c.raddr else ""
family = "ipv6" if ":" in (c.laddr.ip if c.laddr else "") and "." not in (c.laddr.ip if c.laddr else "") else "ipv4"
# better family detection
import socket
family = "ipv6" if (c.family == socket.AF_INET6) else "ipv4"
if c.status == "LISTEN":
listen_list.append({"name": name_by_pid.get(c.pid, ""), "laddr": c.laddr.ip if c.laddr else "", "port": c.laddr.port if c.laddr else 0, "family": family, "pid": c.pid, "proto": "tcp"})
else:
tcp_list.append({"name": name_by_pid.get(c.pid, ""), "laddr": laddr, "raddr": raddr, "family": family, "pid": c.pid, "status": c.status})
except Exception:
pass
tcp_list = tcp_list[:80]
listen_list = listen_list[:80]
return jsonify({"nics": rates, "conns": conns, "items": items,
"hw": get_net_hw(),
"total_recv": total_recv, "total_sent": total_sent,
"tcp": tcp_list, "listen": listen_list})
_net_hw_static = {}
def _net_sysfs(name):
"""实时 sysfs: 状态/MTU/速率/MAC,键名与 psutil 速率互补"""
out = {}
for base in ("/host/sys/class/net", "/sys/class/net"):
d = os.path.join(base, name)
try:
if not os.path.isdir(d):
continue
for k in ("address", "operstate", "mtu", "speed", "duplex",
"carrier"):
v = _read(os.path.join(d, k))
if v:
out[k] = v
# 驱动名
try:
drv = os.path.basename(os.readlink(os.path.join(d, "device/driver")))
if drv:
out["live_driver"] = drv
except Exception:
pass
if out:
break
except Exception:
continue
return out
def _net_addrs():
try:
ad = psutil.net_if_addrs() or {}
except Exception:
return {}
out = {}
for nic, lst in ad.items():
v4, v6, mac = [], [], ""
for a in lst:
try:
fam = a.family.name if hasattr(a.family, "name") else str(a.family)
except Exception:
fam = ""
addr = a.address or ""
if "PACKET" in fam:
if addr:
mac = mac or addr
elif "AF_INET6" in fam:
if addr and not addr.startswith("fe80"):
v6.append(addr.split("%")[0])
elif addr:
v6.append(addr.split("%")[0] + "(链路)")
elif "AF_INET" in fam:
if addr and len(addr.split(".")) == 4:
v4.append(addr)
out[nic] = {"v4": v4, "v6": v6, "mac": mac}
return out
def get_net_hw():
global _net_hw_static
if not _net_hw_static:
hj = {}
for jp in ("hw_net.json",
os.path.join(os.path.dirname(os.path.abspath(__file__)),
"hw_net.json")):
try:
with open(jp) as f:
hj = json.load(f)
if hj.get("nics"):
break
except Exception:
continue
_net_hw_static = hj or {"nics": []}
statics = {x.get("name"): dict(x) for x in _net_hw_static.get("nics", [])}
try:
st = psutil.net_if_stats() or {}
except Exception:
st = {}
addrs = _net_addrs()
# 展示的网卡: 静态档案 + 实际有流量的非虚拟口
names = list(statics.keys())
try:
counters = psutil.net_io_counters(pernic=True) or {}
except Exception:
counters = {}
for nic in counters:
if nic.startswith(("lo", "docker", "br-", "veth")):
continue
if nic not in statics:
names.append(nic)
out = []
for nic in names:
base = dict(statics.get(nic, {"name": nic}))
s = st.get(nic)
if s is not None:
try:
base["isup"] = bool(s.isup)
base["live_speed"] = s.speed or 0
base["live_mtu"] = s.mtu or 0
except Exception:
pass
base.update(_net_sysfs(nic))
a = addrs.get(nic, {})
if a:
base["ipv4"] = a.get("v4", [])
base["ipv6"] = a.get("v6", [])
if a.get("mac") and not base.get("mac"):
base["mac"] = a["mac"]
c = counters.get(nic)
if c is not None:
try:
base["io_sent"] = c.bytes_sent
base["io_recv"] = c.bytes_recv
except Exception:
pass
out.append(base)
# 默认网关/DNS 实时读
gw, dns = _net_hw_static.get("gateway", ""), _net_hw_static.get("dns", "")
base_if = ""
try:
with open("/host/proc/net/route" if os.path.exists("/host/proc/net/route") else "/proc/net/route") as f:
for line in f.read().splitlines()[1:]:
f_ = line.split()
if len(f_) > 2 and f_[1] == "00000000" and f_[7] == "00000000":
import socket, struct
gw = socket.inet_ntoa(struct.pack("<L", int(f_[2], 16)))
base_if = f_[0]
break
except Exception:
pass
try:
rp = "/host/etc/resolv.conf" if os.path.exists("/host/etc/resolv.conf") else "/etc/resolv.conf"
with open(rp) as f:
for line in f:
if line.startswith("nameserver"):
dns = line.split()[1]
break
except Exception:
pass
return {"nics": out, "gateway": gw, "dns": dns,
"egress": base_if,
"snapshot": _net_hw_static.get("snapshot", ""),
"note": _net_hw_static.get("note", "")}
@app.route("/api/kill", methods=["POST"])
def api_kill():
d = request.get_json(force=True, silent=True) or {}
try:
pid = int(d.get("pid", 0))
except Exception:
return jsonify({"ok": False, "error": "pid无效"}), 400
if pid <= 1:
return jsonify({"ok": False, "error": "不能结束该进程"}), 400
try:
os.kill(pid, signal.SIGTERM)
return jsonify({"ok": True})
except ProcessLookupError:
return jsonify({"ok": False, "error": "进程已不存在"}), 404
except PermissionError:
return jsonify({"ok": False, "error": "无权限"}), 403
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.route("/api/health")
def health():
return jsonify({"ok": True})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=PORT)
+9 -4
View File
@@ -52,6 +52,11 @@ button.refresh{background:#20a53a;color:#fff;border:none;border-radius:3px;paddi
<div class="tab" data-t="mem">内存</div> <div class="tab" data-t="mem">内存</div>
<div class="tab" data-t="disk">磁盘</div> <div class="tab" data-t="disk">磁盘</div>
<div class="tab" data-t="net">网络</div> <div class="tab" data-t="net">网络</div>
<div style="margin-left:auto;display:flex;align-items:center;gap:12px;padding-right:16px;font-size:12px">
<span style="color:#999">v1.2.8</span>
<a href="https://nav.88531.cn" target="_blank" style="color:#20a53a;text-decoration:none">资享导航站</a>
<a href="https://gitea.88531.cn/jinghui/fnos-resmon" target="_blank" style="color:#20a53a;text-decoration:none">开源地址</a>
</div>
</div> </div>
<div class="card" id="summary"></div> <div class="card" id="summary"></div>
<div class="cpuinfo" id="cpuinfo" style="display:none"></div> <div class="cpuinfo" id="cpuinfo" style="display:none"></div>
@@ -72,7 +77,7 @@ document.querySelectorAll('.tab').forEach(t=>t.onclick=()=>{document.querySelect
function fmtB(b){if(b==null)return '-';const u=['B','KB','MB','GB','TB'];let i=0;while(b>=1024&&i<4){b/=1024;i++}return b.toFixed(b>=100?0:1)+u[i]} function fmtB(b){if(b==null)return '-';const u=['B','KB','MB','GB','TB'];let i=0;while(b>=1024&&i<4){b/=1024;i++}return b.toFixed(b>=100?0:1)+u[i]}
function fmtR(b){return fmtB(b)+'/s'} function fmtR(b){return fmtB(b)+'/s'}
function esc(s){return String(s==null?'':s).replace(/&/g,'&amp;').replace(/</g,'&lt;')} function esc(s){return String(s==null?'':s).replace(/&/g,'&amp;').replace(/</g,'&lt;')}
async function dropMem(){if(!confirm('回收可回收内存(drop caches)?'))return;const r=await fetch('/api/mem/drop',{method:'POST'});const j=await r.json();alert(j.ok?('已回收,可用 '+fmtB(j.available)):('失败: '+j.error));load(true)} async function dropMem(){if(!confirm('一键回收未使用的内存(drop caches)?'))return;const r=await fetch('/api/mem/drop',{method:'POST'});const j=await r.json();alert(j.ok?('已回收,可用 '+fmtB(j.available)):('失败: '+j.error));load(true)}
async function kill(pid,name){if(!confirm('结束进程 '+name+' (PID '+pid+') ?'))return;const r=await fetch('/api/kill',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({pid})});const j=await r.json();alert(j.ok?'已发送结束信号':('失败: '+j.error));load(true)} async function kill(pid,name){if(!confirm('结束进程 '+name+' (PID '+pid+') ?'))return;const r=await fetch('/api/kill',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({pid})});const j=await r.json();alert(j.ok?'已发送结束信号':('失败: '+j.error));load(true)}
function cmpVal(p,key){ function cmpVal(p,key){
if(key==='name')return String(p.name||''); if(key==='name')return String(p.name||'');
@@ -136,7 +141,7 @@ document.getElementById('sub').textContent=`共 ${j.total} 个进程,显示占
renderHeader(); renderHeader();
B.innerHTML=j.items.map(p=>`<tr><td><a class="proc">${esc(p.name)}</a></td><td class="num">${p.cpu}</td><td class="num">${p.threads}</td><td class="num">${p.pid}</td><td>${esc(p.desc)}</td><td>${esc(p.user)}</td><td class="${p.active?'st-run':'st-sleep'}">${p.status}</td><td><button class="kill" onclick="kill(${p.pid},'${esc(p.name)}')">结束</button></td></tr>`).join(''); B.innerHTML=j.items.map(p=>`<tr><td><a class="proc">${esc(p.name)}</a></td><td class="num">${p.cpu}</td><td class="num">${p.threads}</td><td class="num">${p.pid}</td><td>${esc(p.desc)}</td><td>${esc(p.user)}</td><td class="${p.active?'st-run':'st-sleep'}">${p.status}</td><td><button class="kill" onclick="kill(${p.pid},'${esc(p.name)}')">结束</button></td></tr>`).join('');
}else if(cur==='mem'){ }else if(cur==='mem'){
S.innerHTML=`<div class="stat"><div class="k">内存占用</div><div class="v green">${j.percent}%</div></div><div class="stat"><div class="k">已用 / 总共</div><div class="v num">${fmtB(j.used)} / ${fmtB(j.total)}</div></div><div class="stat"><div class="k">可用 / Swap</div><div class="v num">${fmtB(j.available)} / ${fmtB(j.swap_used)}/${fmtB(j.swap_total)} (Swap ${j.swap_percent||0}%)</div></div><div class="stat"><div class="k">操作</div><div class="v"><button class="kill" onclick="dropMem()">回收可回收内存</button></div></div>`; S.innerHTML=`<div class="stat"><div class="k">内存占用</div><div class="v green">${j.percent}%</div></div><div class="stat"><div class="k">已用 / 总共</div><div class="v num">${fmtB(j.used)} / ${fmtB(j.total)}</div></div><div class="stat"><div class="k">可用 / Swap</div><div class="v num">${fmtB(j.available)} / ${fmtB(j.swap_used)}/${fmtB(j.swap_total)} (Swap ${j.swap_percent||0}%)</div></div><div class="stat"><div class="k">操作</div><div class="v"><button class="kill" onclick="dropMem()">🧹 一键回收未使用的内存</button></div></div>`;
const D=j.detail||{},H2=j.hw||{},DM=H2.dimms||[]; const D=j.detail||{},H2=j.hw||{},DM=H2.dimms||[];
const row=(k,v)=>`<span style="display:inline-block;min-width:230px;margin-right:12px">${k} <b class="num">${v}</b></span>`; const row=(k,v)=>`<span style="display:inline-block;min-width:230px;margin-right:12px">${k} <b class="num">${v}</b></span>`;
document.getElementById('meminfo').style.display=''; document.getElementById('meminfo').style.display='';
@@ -180,8 +185,8 @@ document.getElementById('netinfo').innerHTML=`<div class="model">出口 ${esc(NW
} }
load(true);setInterval(()=>load(false),3000); load(true);setInterval(()=>load(false),3000);
</script> </script>
<footer style="text-align:center;padding:8px;font-size:12px;color:#999;border-top:1px solid #eee"> <footer style="position:fixed;bottom:0;left:0;right:0;text-align:center;padding:6px;font-size:12px;color:#999;background:#fff;border-top:1px solid #eee;z-index:999">
<a href="https://nav.88531.cn" target="_blank" rel="noopener">资享导航站</a> · <a href="https://nav.88531.cn" target="_blank" rel="noopener">资享导航站</a> ·
<a href="http://192.168.68.19:3200/jinghui/fnmon" target="_blank" rel="noopener">开源地址 (Gitea)</a> <a href="https://gitea.88531.cn/jinghui/fnos-resmon" target="_blank" rel="noopener">开源地址 (Gitea)</a>
</footer> </footer>
</html> </html>
+14
View File
@@ -0,0 +1,14 @@
version: '3.8'
services:
fnos-resmon:
image: jpccr.ccs.tencentyun.com/jinghui/fnos-resmon:latest
container_name: fnos-resmon
privileged: true
network_mode: host
pid: host
volumes:
- /proc:/host/proc:rw
- /sys:/host/sys:ro
environment:
- PROCFS_PATH=/host/proc
restart: unless-stopped
Binary file not shown.

After

Width:  |  Height:  |  Size: 329 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 549 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 390 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 614 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 494 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

BIN
View File
Binary file not shown.
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
set -euo pipefail
PORT="${PORT:-7031}"
CONTAINER_NAME="${CONTAINER_NAME:-fnos-resmon}"
INSTALL_DIR="${INSTALL_DIR:-/vol1/1000/HD1/docker/fnos-resmon}"
REPO_URL="https://gitea.88531.cn/jinghui/fnos-resmon.git"
if ! command -v docker >/dev/null 2>&1; then
echo "❌ 未检测到 Docker,请先安装 Docker"; exit 1
fi
if ! docker compose version >/dev/null 2>&1; then
echo "❌ 未检测到 docker compose"; exit 1
fi
if ! command -v git >/dev/null 2>&1; then
echo "❌ 未检测到 git"; exit 1
fi
# 自动探测 docker 根目录
if [ -d /vol1/1000/HD1/docker ]; then
COMPOSE_ROOT=/vol1/1000/HD1/docker
elif [ -d "$HOME/docker" ]; then
COMPOSE_ROOT="$HOME/docker"
else
COMPOSE_ROOT="$(dirname "$INSTALL_DIR")"
fi
if [ -d "$INSTALL_DIR/.git" ]; then
echo "🔄 检测到已有安装,执行更新..."
cd "$INSTALL_DIR"
git fetch origin main
git reset --hard origin/main
else
echo "📥 克隆项目..."
mkdir -p "$(dirname "$INSTALL_DIR")"
git clone "$REPO_URL" "$INSTALL_DIR"
cd "$INSTALL_DIR"
fi
cat > "$INSTALL_DIR/.env" <<EOF
PORT=$PORT
CONTAINER_NAME=$CONTAINER_NAME
COMPOSE_ROOT=$COMPOSE_ROOT
EOF
echo "🐳 启动/更新容器..."
docker compose -f "$INSTALL_DIR/docker-compose.yml" --env-file "$INSTALL_DIR/.env" up -d --build
echo "⏳ 等待服务就绪..."
for i in $(seq 1 30); do
if curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT" | grep -q 200; then
echo "✅ 部署完成!访问 http://<NAS IP>:$PORT"
exit 0
fi
sleep 2
done
echo "⚠️ 服务可能未就绪,请检查 docker logs"
exit 1
+1 -1
View File
@@ -1,5 +1,5 @@
appname: fnos-resmon appname: fnos-resmon
version: 1.2.1 version: 1.2.6
display_name: 飞牛资源管理器 display_name: 飞牛资源管理器
desc: 飞牛 NAS 资源监视器(CPU/内存/磁盘/网络四页签,读取宿主真实数据) desc: 飞牛 NAS 资源监视器(CPU/内存/磁盘/网络四页签,读取宿主真实数据)
arch: x86_64 arch: x86_64
+827
View File
@@ -0,0 +1,827 @@
from flask import Flask, jsonify, request, send_from_directory
import psutil, os, time, signal, threading, subprocess, platform, glob, json, struct
try:
psutil.PROCFS_PATH = os.environ.get("PROCFS_PATH", "/proc")
except Exception:
pass
PROCFS = os.environ.get("PROCFS_PATH", "/host/proc")
if os.path.isdir(PROCFS):
psutil.PROCFS_PATH = PROCFS
app = Flask(__name__, static_folder="public", static_url_path="")
PORT = int(os.environ.get("PORT", "7031"))
# ---------- background sampler ----------
cache = {"procs": [], "cpu": 0.0, "load": [0, 0, 0], "ts": 0}
net_prev = {}
net_rate = {}
def fmt_status(s):
m = {
psutil.STATUS_RUNNING: ("活动", 1),
psutil.STATUS_SLEEPING: ("睡眠", 0),
psutil.STATUS_DISK_SLEEP: ("睡眠", 0),
psutil.STATUS_STOPPED: ("停止", 0),
psutil.STATUS_ZOMBIE: ("僵尸", 0),
}
return m.get(s, ("睡眠", 0))
_uid_cache = {"map": {}, "ts": 0}
def uid_name(uid_str):
# 容器内 /etc/passwd 没有宿主用户,uid 会显示成数字,用宿主 passwd 还原
if not uid_str or not uid_str.isdigit():
return uid_str
now = time.time()
if now - _uid_cache["ts"] > 300:
m = {}
try:
with open("/host/etc/passwd") as f:
for line in f:
p = line.split(":")
if len(p) > 3:
try:
m[p[2]] = p[0]
except Exception:
pass
except Exception:
pass
_uid_cache["map"] = m
_uid_cache["ts"] = now
return _uid_cache["map"].get(uid_str, uid_str)
def sample_procs():
# init cpu percent calculation
for p in psutil.process_iter():
try:
p.cpu_percent(None)
except Exception:
pass
time.sleep(1.0)
procs = []
try:
cpu_total = psutil.cpu_percent(interval=None)
except Exception:
cpu_total = 0
try:
load = list(os.getloadavg())
except Exception:
load = [0, 0, 0]
for p in psutil.process_iter(["pid", "name", "username", "status", "num_threads", "cmdline"]):
try:
with p.oneshot():
cpu = p.cpu_percent(None)
mem = p.memory_percent()
try:
rss = p.memory_info().rss
except Exception:
rss = 0
uss = 0
swap = 0
try:
mfi = p.memory_full_info()
uss = getattr(mfi, "uss", 0) or 0
swap = getattr(mfi, "swap", 0) or 0
except Exception:
pass
try:
io = p.io_counters()
rd, wr = io.read_bytes, io.write_bytes
except Exception:
rd, wr = 0, 0
try:
conns = len(p.net_connections())
except Exception:
conns = 0
info = p.info
name = info.get("name") or ""
cmd = " ".join(info.get("cmdline") or [])[:120]
desc = cmd if cmd else name
st, act = fmt_status(info.get("status"))
if (not act) and (cpu or 0) > 1.0:
st, act = "活动", 1
procs.append({
"name": name[:40], "pid": info["pid"],
"cpu": round(cpu or 0, 2), "mem": round(mem or 0, 2),
"rss": rss, "uss": uss, "swap": swap, "threads": info.get("num_threads") or 0,
"user": uid_name(str(info.get("username") or ""))[:20],
"status": st, "active": act,
"desc": desc[:80], "io_r": rd, "io_w": wr, "conns": conns,
})
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
except Exception:
continue
procs.sort(key=lambda x: x["cpu"], reverse=True)
cache["procs"] = procs
cache["cpu"] = round(cpu_total, 1)
cache["load"] = [round(x, 2) for x in load]
cache["ts"] = time.time()
def sampler_loop():
while True:
try:
sample_procs()
except Exception:
pass
time.sleep(2)
threading.Thread(target=sampler_loop, daemon=True).start()
# warm up immediately in background; serve stale until ready
@app.route("/")
def index():
return send_from_directory("public", "index.html")
@app.route("/api/cpu")
def api_cpu():
active = sum(1 for p in cache["procs"] if p["active"])
return jsonify({"cpu": cache["cpu"], "load": cache["load"],
"active": active, "total": len(cache["procs"]),
"info": get_cpu_info(), "percpu": get_percpu(),
"items": cache["procs"][:100]})
_cpu_static = {}
def _parse_host_cpuinfo():
info = {}
try:
with open("/host/proc/cpuinfo") as f:
txt = f.read()
except Exception:
try:
with open("/proc/cpuinfo") as f:
txt = f.read()
except Exception:
return info
# 取第一个 processor 段的 model name / cache size / cpu MHz
for line in txt.splitlines():
if ":" not in line:
continue
k, v = line.split(":", 1)
k, v = k.strip(), v.strip()
if k == "model name" and "model" not in info:
info["model"] = v
elif k == "cache size" and "cache" not in info:
info["cache"] = v
return info
def _parse_lscpu():
out = {}
try:
txt = subprocess.run(["lscpu"], capture_output=True, text=True,
timeout=5).stdout
except Exception:
return out
for line in txt.splitlines():
if ":" not in line and ":" not in line:
continue
line = line.replace(":", ":")
k, v = line.split(":", 1)
k, v = k.strip(), v.strip()
out[k] = v
return out
def get_cpu_info():
global _cpu_static
if not _cpu_static:
ci = _parse_host_cpuinfo()
lc = _parse_lscpu()
def pick(*keys):
for k in keys:
if k in lc and lc[k]:
return lc[k]
return ""
# L1d/L1i/L2/L3 键名中英文兼容
l1d = pick("L1d 缓存", "L1d cache")
l1i = pick("L1i 缓存", "L1i cache")
l2 = pick("L2 缓存", "L2 cache")
l3 = pick("L3 缓存", "L3 cache")
_cpu_static = {
"model": ci.get("model") or pick("型号名称", "Model name"),
"arch": platform.machine(),
"sockets": pick("座", "Socket(s)"),
"cores_per_socket": pick("每个座的核数", "Core(s) per socket"),
"threads_per_core": pick("每个核的线程数", "Thread(s) per core"),
"l1d": l1d, "l1i": l1i, "l2": l2, "l3": l3,
"cache": ci.get("cache", ""),
}
try:
f = psutil.cpu_freq()
cur = round(f.current, 0) if f else 0
fmin = round(f.min, 0) if f and f.min else 0
fmax = round(f.max, 0) if f and f.max else 0
except Exception:
cur = fmin = fmax = 0
d = dict(_cpu_static)
d.update({
"logical": psutil.cpu_count() or 0,
"physical": psutil.cpu_count(logical=False) or 0,
"freq_cur": cur, "freq_min": fmin, "freq_max": fmax,
})
return d
def get_percpu():
try:
vals = psutil.cpu_percent(interval=None, percpu=True)
return [round(v, 1) for v in (vals or [])]
except Exception:
return []
@app.route("/api/mem")
def api_mem():
vm = psutil.virtual_memory()
sm = psutil.swap_memory()
items = sorted(cache["procs"], key=lambda x: x["mem"], reverse=True)[:100]
mi = _read_meminfo_host()
dm = get_mem_hw()
return jsonify({
"total": vm.total, "used": vm.used, "available": vm.available,
"percent": vm.percent, "cached": getattr(vm, "cached", 0),
"swap_total": sm.total, "swap_used": sm.used, "swap_percent": sm.percent,
"detail": mi, "hw": dm,
"items": items})
_mem_hw_static = {}
def _read_meminfo_host():
mi = {}
for p in ("/host/proc/meminfo", "/proc/meminfo"):
try:
with open(p) as f:
for line in f:
if ":" not in line:
continue
k, v = line.split(":", 1)
parts = v.strip().split()
if not parts:
continue
try:
num = int(parts[0])
except ValueError:
continue
# 统一转 bytes
if len(parts) > 1 and parts[1] == "kB":
num *= 1024
mi[k.strip()] = num
if mi:
break
except Exception:
continue
return mi
def _walk_dmi(path):
"""yield (type, raw_bytes, strings)"""
try:
with open(path, "rb") as f:
data = f.read()
except Exception:
return
off, n = 0, 0
L = len(data)
while off + 4 <= L and n < 200:
typ, ln = data[off], data[off + 1]
if ln < 4 or off + ln > L:
break
if typ == 127: # end of table
break
s = off + ln
strs = []
ok = True
while s < L:
try:
e = data.index(b"\x00", s)
except ValueError:
ok = False
break
if e == s:
s += 1
break
strs.append(data[s:e].decode("utf-8", "replace").strip())
s = e + 1
if not ok:
break
yield typ, data[off:off + ln], strs
off = s
n += 1
_MEM_TYPE = {0x02: "Unknown", 0x03: "DRAM", 0x12: "DDR", 0x13: "DDR2",
0x14: "DDR2 FB-DIMM", 0x18: "DDR3", 0x19: "FBD2", 0x1A: "DDR4",
0x1B: "LPDDR", 0x1C: "LPDDR2", 0x1D: "LPDDR3", 0x1E: "LPDDR4",
0x1F: "Logical NV", 0x20: "HBM", 0x21: "HBM2", 0x22: "DDR5",
0x23: "LPDDR5", 0x24: "HBM3"}
def _parse_dmi_mem():
dimms, max_cap_kb = [], 0
for dmi_path in ("/host/sys/firmware/dmi/tables/DMI",
"/sys/firmware/dmi/tables/DMI"):
found = False
for typ, raw, strs in _walk_dmi(dmi_path):
found = True
def S(i):
return strs[i - 1] if 1 <= i <= len(strs) else ""
if typ == 16 and len(raw) >= 11:
import struct
(cap,) = struct.unpack_from("<I", raw, 7)
if cap not in (0, 0x80000000):
max_cap_kb = cap # SMBIOS 单位 kB
elif typ == 17 and len(raw) >= 28:
import struct
(size,) = struct.unpack_from("<H", raw, 12)
if size == 0 or size == 0xFFFF:
continue # 空槽
if size & 0x8000:
mb = size & 0x7FFF # bit15=1 时单位 KB→转MB(向上)
size_mb = max(mb // 1024, 1) if mb >= 1024 else 1
size_b = (size & 0x7FFF) * 1024
else:
size_mb = size & 0x7FFF
size_b = size_mb * 1024 * 1024
if size_mb == 0x7FFF:
continue
(speed,) = struct.unpack_from("<H", raw, 20)
cspeed = 0
if len(raw) >= 30:
(cspeed,) = struct.unpack_from("<H", raw, 28)
mtype = raw[18] if len(raw) > 18 else 0
dimms.append({
"locator": S(raw[16]) if len(raw) > 16 else "",
"bank": S(raw[17]) if len(raw) > 17 else "",
"size_b": size_b, "size_mb": size_mb,
"type": _MEM_TYPE.get(mtype, "DDR4" if mtype == 0 else hex(mtype)),
"speed": speed or 0, "cspeed": cspeed or 0,
"maker": S(raw[22]) if len(raw) > 22 else "",
"serial": S(raw[23]) if len(raw) > 23 else "",
"part": S(raw[25]) if len(raw) > 25 else "",
})
if found:
break
return dimms, max_cap_kb
def _get_vram():
total = 0
for base in ("/host/sys/class/drm", "/sys/class/drm"):
try:
for p in glob.glob(base + "/card*/device/mem_info_vram_total"):
try:
with open(p) as f:
total += int(f.read().strip())
except Exception:
pass
except Exception:
pass
if total:
break
return total
def get_mem_hw():
global _mem_hw_static
if not _mem_hw_static:
dimms, max_cap_kb = [], 0
# 优先读构建时从宿主 dmidecode 导出的静态槽位表
for jp in ("hw_mem.json",
os.path.join(os.path.dirname(os.path.abspath(__file__)),
"hw_mem.json")):
try:
with open(jp) as f:
hj = json.load(f)
dimms = hj.get("dimms", []) or []
max_cap_kb = int((hj.get("max_cap_b", 0) or 0) // 1024)
if dimms:
break
except Exception:
continue
if not dimms:
dimms, max_cap_kb = _parse_dmi_mem()
installed = sum(d["size_b"] for d in dimms)
_mem_hw_static = {"dimms": dimms, "installed": installed,
"max_cap_kb": max_cap_kb}
d = {"dimms": _mem_hw_static["dimms"],
"installed": _mem_hw_static["installed"],
"max_cap_kb": _mem_hw_static["max_cap_kb"]}
try:
mem_total = psutil.virtual_memory().total
except Exception:
mem_total = 0
d["vram"] = _get_vram()
d["system_total"] = mem_total
d["reserved"] = (d["installed"] - mem_total) if d["installed"] and mem_total else 0
return d
HOST_MNTS = [("/", "/host"), ("/vol1", "/host/vol1"),
("/vol2", "/host/vol2"), ("/vol3", "/host/vol3")]
def _df_host():
"""容器内 df 直读宿主路径(经 bind 进来的宿主目录),返回 {mnt: {...}}"""
try:
out = subprocess.run(
["df", "-B1", "--output=source,target,fstype,size,used,avail",
"/host", "/host/vol1", "/host/vol2", "/host/vol3"],
capture_output=True, text=True, timeout=5).stdout.splitlines()
res = {}
for line in out[1:]:
p = line.split()
if len(p) < 6:
continue
dev, tgt, fst, size, used, avail = p[0], p[1], p[2], int(p[3]), int(p[4]), int(p[5])
mnt = tgt.replace("/host", "", 1) or "/"
res[mnt] = {"device": dev, "mount": mnt, "fstype": fst,
"total": size, "used": used, "free": avail,
"percent": round(used / size * 100, 1) if size else 0}
return res
except Exception:
return {}
@app.route("/api/mem/drop", methods=["POST"])
def api_mem_drop():
import subprocess
try:
subprocess.run(["sync"], check=False, timeout=10)
p = os.environ.get("PROCFS_PATH", "/proc")
with open(os.path.join(p, "sys", "vm", "drop_caches"), "w") as f:
f.write("3")
vm = psutil.virtual_memory()
return jsonify({"ok": True, "available": vm.available, "percent": vm.percent})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.route("/api/disk")
def api_disk():
parts = []
dfm = _df_host()
for mp, hp in HOST_MNTS:
if mp in dfm:
parts.append(dfm[mp])
continue
try:
st = os.statvfs(hp)
total = st.f_blocks * st.f_frsize
free = st.f_bavail * st.f_frsize
used = total - free
parts.append({"device": "?", "mount": mp, "fstype": "?",
"total": total, "used": used, "free": free,
"percent": round(used / total * 100, 1) if total else 0})
except Exception:
continue
try:
dio = psutil.disk_io_counters()
dio_d = {"read": dio.read_bytes, "write": dio.write_bytes} if dio else {}
except Exception:
dio_d = {}
# top io processes
items = sorted(cache["procs"], key=lambda x: x["io_r"] + x["io_w"], reverse=True)[:60]
return jsonify({"parts": parts, "io": dio_d, "hw": get_disk_hw(),
"items": items})
_disk_hw_static = {}
def _read(p, default=""):
try:
with open(p) as f:
return f.read().strip()
except Exception:
return default
def _sys_block_base():
for base in ("/host/sys/block", "/sys/block"):
try:
if os.path.isdir(base):
return base
except Exception:
continue
return "/host/sys/block"
def _live_sysfs(name):
"""实时 sysfs: 容量/转速/型号(覆盖静态快照中的漂移项)"""
base = _sys_block_base()
d = os.path.join(base, name)
out = {}
try:
sectors = _read(os.path.join(d, "size"))
if sectors.isdigit():
out["cap_b"] = int(sectors) * 512
except Exception:
pass
rot = _read(os.path.join(d, "queue/rotational"))
if rot in ("0", "1"):
out["rotational"] = (rot == "1")
model = _read(os.path.join(d, "device/model"))
if model:
out["sys_model"] = model
vendor = _read(os.path.join(d, "device/vendor"))
if vendor:
out["sys_vendor"] = vendor
return out
def _live_mdstat():
"""实时 mdstat: 每组阵列状态/同步进度,键为 md 名"""
st = {}
for p in ("/host/proc/mdstat", "/proc/mdstat"):
try:
with open(p) as f:
txt = f.read()
break
except Exception:
txt = ""
else:
return st
import re
cur = None
for line in txt.splitlines():
m = re.match(r"^(md\d+)\s*:\s*(\w+)\s+(\w+)(.*)$", line)
if m:
cur = m.group(1)
st[cur] = {"status": m.group(2), "level": m.group(3),
"devs": m.group(4).strip(), "sync": ""}
continue
if cur and ("recovery" in line or "resync" in line or "blocks" in line):
s = line.strip()
if "recovery" in line or "resync" in line:
st[cur]["sync"] = s
elif "blocks" in line and not st[cur].get("blocks"):
st[cur]["blocks"] = s
return st
def _live_perdisk_io():
try:
d = psutil.disk_io_counters(perdisk=True) or {}
except Exception:
return {}
out = {}
for k, v in d.items():
try:
out[k] = {"read": v.read_bytes, "write": v.write_bytes}
except Exception:
continue
return out
def get_disk_hw():
global _disk_hw_static
if not _disk_hw_static:
hj = {}
for jp in ("hw_disk.json",
os.path.join(os.path.dirname(os.path.abspath(__file__)),
"hw_disk.json")):
try:
with open(jp) as f:
hj = json.load(f)
if hj.get("disks"):
break
except Exception:
continue
_disk_hw_static = hj or {"disks": [], "arrays": []}
disks = [dict(x) for x in _disk_hw_static.get("disks", [])]
arrays = [dict(x) for x in _disk_hw_static.get("arrays", [])]
# 合并实时数据
pio = _live_perdisk_io()
for dk in disks:
nm = dk.get("name", "")
dk.update(_live_sysfs(nm))
if nm in pio:
dk["io_read"] = pio[nm]["read"]
dk["io_write"] = pio[nm]["write"]
# 转速文字
if dk.get("rotational") is True and not dk.get("rpm"):
dk["rpm"] = 5400
md_live = _live_mdstat()
for a in arrays:
md = a.get("md", "")
lv = md_live.get(md, {})
if lv:
a["live_status"] = lv.get("status", "")
a["live_devs"] = lv.get("devs", "")
a["live_sync"] = lv.get("sync", "")
if md in pio:
a["io_read"] = pio[md]["read"]
a["io_write"] = pio[md]["write"]
return {"disks": disks, "arrays": arrays,
"extra": _disk_hw_static.get("extra", {}),
"snapshot": _disk_hw_static.get("snapshot", ""),
"note": _disk_hw_static.get("note", "")}
@app.route("/api/net")
def api_net():
global net_prev, net_rate
now = time.time()
try:
counters = psutil.net_io_counters(pernic=True)
except Exception:
counters = {}
rates = []
for nic, c in counters.items():
if nic.startswith(("lo", "docker", "br-", "veth")):
continue
prev = net_prev.get(nic)
if prev:
dt = max(now - prev["t"], 0.5)
up = (c.bytes_sent - prev["sent"]) / dt
down = (c.bytes_recv - prev["recv"]) / dt
else:
up = down = 0
net_prev[nic] = {"sent": c.bytes_sent, "recv": c.bytes_recv, "t": now}
rates.append({"nic": nic, "up": max(up, 0), "down": max(down, 0),
"sent": c.bytes_sent, "recv": c.bytes_recv})
rates.sort(key=lambda x: x["up"] + x["down"], reverse=True)
try:
conns = len(psutil.net_connections())
except Exception:
conns = 0
total_recv = 0
total_sent = 0
for nic, c in counters.items():
if nic.startswith(("lo", "docker", "br-", "veth")):
continue
total_recv += getattr(c, "bytes_recv", 0) or 0
total_sent += getattr(c, "bytes_sent", 0) or 0
items = sorted(cache["procs"], key=lambda x: x["conns"], reverse=True)[:60]
tcp_list = []
listen_list = []
try:
name_by_pid = {p["pid"]: p["name"] for p in cache.get("procs", [])}
for c in psutil.net_connections(kind="tcp"):
laddr = f"{c.laddr.ip}:{c.laddr.port}" if c.laddr else ""
raddr = f"{c.raddr.ip}:{c.raddr.port}" if c.raddr else ""
family = "ipv6" if ":" in (c.laddr.ip if c.laddr else "") and "." not in (c.laddr.ip if c.laddr else "") else "ipv4"
# better family detection
import socket
family = "ipv6" if (c.family == socket.AF_INET6) else "ipv4"
if c.status == "LISTEN":
listen_list.append({"name": name_by_pid.get(c.pid, ""), "laddr": c.laddr.ip if c.laddr else "", "port": c.laddr.port if c.laddr else 0, "family": family, "pid": c.pid, "proto": "tcp"})
else:
tcp_list.append({"name": name_by_pid.get(c.pid, ""), "laddr": laddr, "raddr": raddr, "family": family, "pid": c.pid, "status": c.status})
except Exception:
pass
tcp_list = tcp_list[:80]
listen_list = listen_list[:80]
return jsonify({"nics": rates, "conns": conns, "items": items,
"hw": get_net_hw(),
"total_recv": total_recv, "total_sent": total_sent,
"tcp": tcp_list, "listen": listen_list})
_net_hw_static = {}
def _net_sysfs(name):
"""实时 sysfs: 状态/MTU/速率/MAC,键名与 psutil 速率互补"""
out = {}
for base in ("/host/sys/class/net", "/sys/class/net"):
d = os.path.join(base, name)
try:
if not os.path.isdir(d):
continue
for k in ("address", "operstate", "mtu", "speed", "duplex",
"carrier"):
v = _read(os.path.join(d, k))
if v:
out[k] = v
# 驱动名
try:
drv = os.path.basename(os.readlink(os.path.join(d, "device/driver")))
if drv:
out["live_driver"] = drv
except Exception:
pass
if out:
break
except Exception:
continue
return out
def _net_addrs():
try:
ad = psutil.net_if_addrs() or {}
except Exception:
return {}
out = {}
for nic, lst in ad.items():
v4, v6, mac = [], [], ""
for a in lst:
try:
fam = a.family.name if hasattr(a.family, "name") else str(a.family)
except Exception:
fam = ""
addr = a.address or ""
if "PACKET" in fam:
if addr:
mac = mac or addr
elif "AF_INET6" in fam:
if addr and not addr.startswith("fe80"):
v6.append(addr.split("%")[0])
elif addr:
v6.append(addr.split("%")[0] + "(链路)")
elif "AF_INET" in fam:
if addr and len(addr.split(".")) == 4:
v4.append(addr)
out[nic] = {"v4": v4, "v6": v6, "mac": mac}
return out
def get_net_hw():
global _net_hw_static
if not _net_hw_static:
hj = {}
for jp in ("hw_net.json",
os.path.join(os.path.dirname(os.path.abspath(__file__)),
"hw_net.json")):
try:
with open(jp) as f:
hj = json.load(f)
if hj.get("nics"):
break
except Exception:
continue
_net_hw_static = hj or {"nics": []}
statics = {x.get("name"): dict(x) for x in _net_hw_static.get("nics", [])}
try:
st = psutil.net_if_stats() or {}
except Exception:
st = {}
addrs = _net_addrs()
# 展示的网卡: 静态档案 + 实际有流量的非虚拟口
names = list(statics.keys())
try:
counters = psutil.net_io_counters(pernic=True) or {}
except Exception:
counters = {}
for nic in counters:
if nic.startswith(("lo", "docker", "br-", "veth")):
continue
if nic not in statics:
names.append(nic)
out = []
for nic in names:
base = dict(statics.get(nic, {"name": nic}))
s = st.get(nic)
if s is not None:
try:
base["isup"] = bool(s.isup)
base["live_speed"] = s.speed or 0
base["live_mtu"] = s.mtu or 0
except Exception:
pass
base.update(_net_sysfs(nic))
a = addrs.get(nic, {})
if a:
base["ipv4"] = a.get("v4", [])
base["ipv6"] = a.get("v6", [])
if a.get("mac") and not base.get("mac"):
base["mac"] = a["mac"]
c = counters.get(nic)
if c is not None:
try:
base["io_sent"] = c.bytes_sent
base["io_recv"] = c.bytes_recv
except Exception:
pass
out.append(base)
# 默认网关/DNS 实时读
gw, dns = _net_hw_static.get("gateway", ""), _net_hw_static.get("dns", "")
base_if = ""
try:
with open("/host/proc/net/route" if os.path.exists("/host/proc/net/route") else "/proc/net/route") as f:
for line in f.read().splitlines()[1:]:
f_ = line.split()
if len(f_) > 2 and f_[1] == "00000000" and f_[7] == "00000000":
import socket, struct
gw = socket.inet_ntoa(struct.pack("<L", int(f_[2], 16)))
base_if = f_[0]
break
except Exception:
pass
try:
rp = "/host/etc/resolv.conf" if os.path.exists("/host/etc/resolv.conf") else "/etc/resolv.conf"
with open(rp) as f:
for line in f:
if line.startswith("nameserver"):
dns = line.split()[1]
break
except Exception:
pass
return {"nics": out, "gateway": gw, "dns": dns,
"egress": base_if,
"snapshot": _net_hw_static.get("snapshot", ""),
"note": _net_hw_static.get("note", "")}
@app.route("/api/kill", methods=["POST"])
def api_kill():
d = request.get_json(force=True, silent=True) or {}
try:
pid = int(d.get("pid", 0))
except Exception:
return jsonify({"ok": False, "error": "pid无效"}), 400
if pid <= 1:
return jsonify({"ok": False, "error": "不能结束该进程"}), 400
try:
os.kill(pid, signal.SIGTERM)
return jsonify({"ok": True})
except ProcessLookupError:
return jsonify({"ok": False, "error": "进程已不存在"}), 404
except PermissionError:
return jsonify({"ok": False, "error": "无权限"}), 403
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.route("/api/health")
def health():
return jsonify({"ok": True})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=PORT)