# 创建虚拟环境目录 python3 -m venv /sda1/xunjian/venv # 激活虚拟环境 source /sda1/xunjian/venv/bin/activate # 激活后终端会显示 (venv)

  1. 创建虚拟环境(在当前目录):

    bash

    python3 -m venv venv
    

  2. 激活虚拟环境

    bash

    source venv/bin/activate  # 激活后终端会显示 (venv)
    

  3. 在虚拟环境中安装依赖(此时无权限限制):

    bash

    pip install flask psutil
    

  4. 运行脚本(需在虚拟环境中):

    bash

    python xun.py
    

完成后,若要退出虚拟环境,执行:

bash

deactivate

虚拟环境能完全隔离项目依赖,避免影响系统 Python 环境,是标准且安全的做法。

安装依赖(在虚拟环境中):

pip install flask paramiko

import psutil
import subprocess
import time
import paramiko
from flask import Flask, render_template_string, jsonify
from threading import Thread, Lockapp = Flask(__name__)
lock = Lock()# 监控配置:本地 + 远程机器(修改远程机器SSH信息)
MONITOR_CONFIG = {"local": {"name": "本地服务器","type": "local"},"remote-1": {"name": "远程服务器 (192.168.1.7)","type": "remote","ip": "192.168.1.7","username": "your_ssh_username",  # 替换为远程SSH用户名"password": "your_ssh_password",  # 替换为远程SSH密码"services": ["nginx", "mysql", "ssh"]  # 远程监控服务}
}# 本地监控服务列表
LOCAL_SERVICES = ["nginx", "mysql", "docker"]# -------------------------- 工具函数:单位转换(核心修复) --------------------------
def convert_to_gb(value_str):"""将带单位的存储值(如462M、2.5G)转换为GB的浮点数"""if not value_str:return 0.0value_str = value_str.strip().upper()if 'G' in value_str:return float(value_str.replace('G', ''))elif 'M' in value_str:return float(value_str.replace('M', '')) / 1024  # M转Gelif 'K' in value_str:return float(value_str.replace('K', '')) / (1024 **2)  # K转Gelse:return 0.0# -------------------------- 本地机器监控 --------------------------
def get_local_system_info():"""获取本地系统资源信息(修复状态判断)"""# CPUcpu_percent = psutil.cpu_percent(interval=1)cpu_cores = psutil.cpu_count(logical=False)# 内存memory = psutil.virtual_memory()memory_used = round(memory.used / (1024** 3), 2)memory_total = round(memory.total / (1024 **3), 2)# 磁盘(根目录)disk = psutil.disk_usage('/')disk_used = round(disk.used / (1024** 3), 2)disk_total = round(disk.total / (1024 **3), 2)# Swapswap = psutil.swap_memory()swap_used = round(swap.used / (1024** 3), 2)swap_total = round(swap.total / (1024 **3), 2)return {"cpu": {"percent": cpu_percent, "cores": cpu_cores},"memory": {"used": memory_used, "total": memory_total, "percent": memory.percent},"disk": {"used": disk_used, "total": disk_total, "percent": disk.percent},"swap": {"used": swap_used, "total": swap_total, "percent": swap.percent}}def check_local_service_status(service):"""检查本地服务状态"""try:result = subprocess.run(f"systemctl is-active {service}",shell=True,capture_output=True,text=True)return result.stdout.strip() == "active"except:for p in psutil.process_iter(["name"]):if service in p.info["name"].lower():return Truereturn False# -------------------------- 远程机器监控(核心修复) --------------------------
def ssh_exec_command(ip, username, password, command):"""通过SSH执行远程命令"""ssh = paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())try:ssh.connect(ip, username=username, password=password, timeout=10)stdin, stdout, stderr = ssh.exec_command(command)output = stdout.read().decode().strip()error = stderr.read().decode().strip()return output, errorexcept Exception as e:return None, str(e)finally:ssh.close()def get_remote_system_info(config):"""获取远程系统资源信息(修复单位转换错误)"""ip = config["ip"]username = config["username"]password = config["password"]# CPU使用率(修复命令,兼容更多系统)cpu_output, err = ssh_exec_command(ip, username, password, "grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage}'")cpu_percent = float(cpu_output) if cpu_output and cpu_output.replace('.', '', 1).isdigit() else 0.0# 内存信息(处理M/GB单位)mem_output, err = ssh_exec_command(ip, username, password, "free -h | grep Mem | awk '{print $3, $2}'"  # 只取已用和总量(如"462M 1.8G"))mem_used = 0.0mem_total = 0.0mem_percent = 0.0if mem_output and len(mem_output.split()) == 2:mem_used_str, mem_total_str = mem_output.split()mem_used = convert_to_gb(mem_used_str)mem_total = convert_to_gb(mem_total_str)mem_percent = (mem_used / mem_total) * 100 if mem_total > 0 else 0.0# 磁盘信息(处理M/GB单位)disk_output, err = ssh_exec_command(ip, username, password, "df -h / | tail -1 | awk '{print $3, $2}'"  # 已用和总量(如"5.8G 6.3G"))disk_used = 0.0disk_total = 0.0disk_percent = 0.0if disk_output and len(disk_output.split()) == 2:disk_used_str, disk_total_str = disk_output.split()disk_used = convert_to_gb(disk_used_str)disk_total = convert_to_gb(disk_total_str)disk_percent = (disk_used / disk_total) * 100 if disk_total > 0 else 0.0# Swap信息(处理M/GB单位)swap_output, err = ssh_exec_command(ip, username, password, "free -h | grep Swap | awk '{print $3, $2}'")swap_used = 0.0swap_total = 0.0swap_percent = 0.0if swap_output and len(swap_output.split()) == 2:swap_used_str, swap_total_str = swap_output.split()swap_used = convert_to_gb(swap_used_str)swap_total = convert_to_gb(swap_total_str)swap_percent = (swap_used / swap_total) * 100 if swap_total > 0 else 0.0return {"cpu": {"percent": round(cpu_percent, 1), "cores": 0},"memory": {"used": round(mem_used, 2), "total": round(mem_total, 2), "percent": round(mem_percent, 1)},"disk": {"used": round(disk_used, 2), "total": round(disk_total, 2), "percent": round(disk_percent, 1)},"swap": {"used": round(swap_used, 2), "total": round(swap_total, 2), "percent": round(swap_percent, 1)}}def check_remote_service_status(config, service):"""检查远程服务状态(确保返回布尔值)"""ip = config["ip"]username = config["username"]password = config["password"]# 先检查systemctl状态output, err = ssh_exec_command(ip, username, password, f"systemctl is-active {service}")if output == "active":return True# 再检查进程output, err = ssh_exec_command(ip, username, password, f"pgrep -x {service} >/dev/null 2>&1 && echo 'running'")return output == "running"# -------------------------- 数据更新线程 --------------------------
def update_monitor_data():"""定期更新所有机器的监控数据(修复状态显示)"""while True:with lock:# 本地机器数据(明确标记为online)try:local_system = get_local_system_info()local_services = [{"name": s, "is_running": check_local_service_status(s)}for s in LOCAL_SERVICES]monitor_data["local"] = {"name": MONITOR_CONFIG["local"]["name"],"system": local_system,"services": local_services,"update_time": time.strftime('%Y-%m-%d %H:%M:%S'),"status": "online"  # 本地默认在线}except Exception as e:monitor_data["local"] = {"name": MONITOR_CONFIG["local"]["name"],"error": str(e),"status": "offline","update_time": time.strftime('%Y-%m-%d %H:%M:%S')}# 远程机器数据(完善错误处理)remote_config = MONITOR_CONFIG["remote-1"]try:remote_system = get_remote_system_info(remote_config)# 确保服务列表不为空remote_services = []for s in remote_config["services"]:try:remote_services.append({"name": s,"is_running": check_remote_service_status(remote_config, s)})except:remote_services.append({"name": s,"is_running": False})monitor_data["remote-1"] = {"name": remote_config["name"],"system": remote_system,"services": remote_services,"update_time": time.strftime('%Y-%m-%d %H:%M:%S'),"status": "online"}except Exception as e:# 即使出错,也返回空服务列表避免前端undefinedmonitor_data["remote-1"] = {"name": remote_config["name"],"error": f"连接失败: {str(e)}","services": [{"name": s, "is_running": False} for s in remote_config["services"]],"status": "offline","update_time": time.strftime('%Y-%m-%d %H:%M:%S')}time.sleep(10)  # 每10秒更新一次# 初始化监控数据存储
monitor_data = {}
# 启动更新线程
update_thread = Thread(target=update_monitor_data, daemon=True)
update_thread.start()# -------------------------- Web页面与API --------------------------
@app.route('/')
def index():return render_template_string('''
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>多机器监控仪表盘</title><script src="https://cdn.tailwindcss.com"></script><link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet"><style>.machine-card {border: 1px solid #e2e8f0;border-radius: 0.5rem;padding: 1rem;margin-bottom: 1rem;}.status-running { color: #10b981; }.status-stopped { color: #ef4444; }.status-online { color: #10b981; }.status-offline { color: #ef4444; }</style>
</head>
<body class="bg-gray-50 p-4"><h1 class="text-2xl font-bold mb-6">多机器监控仪表盘</h1><div id="monitor-data"><!-- 数据将通过JS动态填充 --></div><script>function formatData() {fetch('/api/data').then(res => res.json()).then(data => {let html = '';for (let key in data) {const machine = data[key];// 处理未定义的系统数据const system = machine.system || {cpu: {percent: 0},memory: {used: 0, total: 0},disk: {used: 0, total: 0},swap: {used: 0, total: 0}};// 处理未定义的服务const services = machine.services || [];html += `<div class="machine-card"><h2 class="text-xl font-semibold mb-4">${machine.name} <span class="text-sm ml-2 ${machine.status === 'online' ? 'status-online' : 'status-offline'}">${machine.status === 'online' ? '在线' : '离线'}</span></h2>${machine.error ? `<p class="text-red-500 mb-4 text-sm">${machine.error}</p>` : ''}<div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6"><div class="bg-white p-3 rounded shadow"><h3 class="text-sm text-gray-500">CPU使用率</h3><p class="text-xl font-bold">${system.cpu.percent.toFixed(1)}%</p></div><div class="bg-white p-3 rounded shadow"><h3 class="text-sm text-gray-500">内存使用</h3><p class="text-xl font-bold">${system.memory.used.toFixed(2)}G/${system.memory.total.toFixed(2)}G</p></div><div class="bg-white p-3 rounded shadow"><h3 class="text-sm text-gray-500">磁盘使用</h3><p class="text-xl font-bold">${system.disk.used.toFixed(2)}G/${system.disk.total.toFixed(2)}G</p></div><div class="bg-white p-3 rounded shadow"><h3 class="text-sm text-gray-500">Swap使用</h3><p class="text-xl font-bold">${system.swap.used.toFixed(2)}G/${system.swap.total.toFixed(2)}G</p></div></div><div class="mb-2"><h3 class="text-lg font-medium mb-2">服务状态</h3><div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2">${services.map(s => `<div class="bg-white p-2 rounded shadow flex justify-between items-center"><span>${s.name}</span><span class="${s.is_running ? 'status-running' : 'status-stopped'}"><i class="fa ${s.is_running ? 'fa-check-circle' : 'fa-times-circle'}"></i>${s.is_running ? '运行中' : '已停止'}</span></div>`).join('')}</div></div><p class="text-xs text-gray-500">最后更新: ${machine.update_time}</p></div>`;}document.getElementById('monitor-data').innerHTML = html;});}// 初始加载和定时刷新formatData();setInterval(formatData, 10000);</script>
</body>
</html>''')@app.route('/api/data')
def api_data():with lock:return jsonify(monitor_data)if __name__ == '__main__':app.run(host='0.0.0.0', port=5000, debug=True)

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/915616.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/915616.shtml
英文地址,请注明出处:http://en.pswp.cn/news/915616.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

VUE2 项目学习笔记 ? 语法 v-if/v-show

?语法页面渲染的时候&#xff0c;需要服务器传过来的对象中的一个属性&#xff0c;然后根据这个属性用v-for渲染标签&#xff0c;这里写的v-for".... in dataList.goodsList"但是当解析到这行语法的时候&#xff0c;dataList还没返回&#xff0c;因此控制台会报错找…

使用qemu命令启动虚拟机

1. 安装相关软件 yum install qemu edk2* libvirt -y 启动libvirt服务 systemctl start libvirtd systemctl status libvirtd2. 创建虚拟机 2.1. qemu启动命令示例 /usr/bin/qemu-system-loongarch64 \-machine virt,accelkvm \-nodefaults \-m 2048 \-smp 2,maxcpus4,co…

大模型系统化学习路线

人工智能大模型系统化学习路线一、基础理论筑基&#xff08;1-2个月) 目标&#xff1a;建立大模型核心认知框架 核心内容&#xff1a; 深度学习基础&#xff1a;神经网络原理、CNN/RNN结构、梯度下降算法大模型本质&#xff1a;Transformer架构&#xff08;重点掌握注意力机制、…

LLaMA-Factory 微调可配置的模型基本参数

LLaMA-Factory 微调可配置的模型基本参数 flyfish 基本参数 一、模型加载与路径配置参数名类型描述默认值model_name_or_pathOptional[str]模型路径&#xff08;本地路径或 Huggingface/ModelScope 路径&#xff09;。Noneadapter_name_or_pathOptional[str]适配器路径&#xf…

Ubuntu 22 安装 ZooKeeper 3.9.3 记录

Ubuntu 22 安装 ZooKeeper 3.9.3 记录 本文记录在 Ubuntu 22.04 系统上安装 ZooKeeper 3.9.3 的过程&#xff0c;包含 Java 环境准备、配置文件调整、启动与停机操作、以及如何将 ZooKeeper 注册为系统服务。 一、准备环境 ZooKeeper 3.9.x 要求 Java 11 或更高版本&#xff…

FreeSwitch通过Websocket(流式双向语音)对接AI实时语音大模型技术方案(mod_ppy_aduio_stream)

FreeSwitch通过WebSocket对接AI实时语音大模型插件技术方案1. 方案概述 基于FreeSWITCH的实时通信能力&#xff0c;通过WebSocket协议桥接AI大模型服务&#xff0c;实现低延迟、高并发的智能语音交互系统。支持双向语音流处理、实时ASR/TTS转换和动态业务指令执行。 1753095153…

航班调度优化策略全局概览

在机场关闭场景下的航班恢复工作&#xff0c;是将机场关闭期间所有的航班进行取消然后恢复还是将机场关闭期间航班全部延误而后调整呢&#xff1f;简单来说&#xff0c;在实际操作中&#xff0c;既不是无差别地全部取消&#xff0c;也不是无差别地全部延误。这两种“一刀切”的…

spring boot 异步线程@Async 传递 threadLocal数据

将父类的 threadLocal 的数据 在线程池时&#xff0c;可以转给子线程使用。 Async 的使用。 第一步在启动服务加上 EnableAsync 注解。 EnableAsync public class NetCoreApplication {... ... }第二步&#xff1a;导入阿里 线程工具类<dependency><groupId>com.a…

AI产品经理成长记《零号列车》第一集 邂逅0XAI列车

《零号列车》绝非传统意义上的 AI 产品经理教程 —— 它是我沉淀二十多年跨行业数字化转型与工业 4.0 实战经验后,首创的100集大型小说体培养指南。那些曾在千行百业验证过的知识与经验,不再是枯燥的文字堆砌,而是化作一场沉浸式的学习旅程。​ 这里没有生硬的理论灌输,而…

[C++11]范围for循环/using使用

范围for循环 范围for循环&#xff08;Range-based for loop&#xff09;是 C11 引入的一种简洁的循环语法&#xff0c;用于遍历容器中的元素或者其他支持迭代的数据结构。 范围for循环可以让代码更加简洁和易读&#xff0c;避免了传统for循环中索引的操作。 下面是范围for循环的…

简单了解下npm、yarn 和 pnpm 中 add 与 install(i) 命令的区别(附上两图带你一目明了)

目录 pnpm 中 add 和 i 的区别 npm 中 add 和 i 的区别 yarn 中 add 和 i 的区别 附上两图带你一目明了&#xff1a; npm、yarn和pnpm的三者区别图&#xff1a; i 和 add 的核心区别图&#xff1a; 个人建议&#xff1a;在项目中保持命令使用的一致性&#xff0c;选择一种…

ESP32-S3学习笔记<2>:GPIO的应用

ESP32-S3学习笔记&#xff1c;2&#xff1e;&#xff1a;GPIO的应用1. 头文件包含2. GPIO的配置2.1 pin_bit_mask2.2 mode2.3 pull_up_en和pull_down_en2.4 intr_type3. 设置GPIO输出/获取GPIO输入4. 中断的使用4.1 gpio_install_isr_service4.2 gpio_isr_handler_add4.3 gpio_…

得物视觉算法面试30问全景精解

得物视觉算法面试30问全景精解 ——潮流电商 商品鉴别 视觉智能&#xff1a;得物视觉算法面试核心考点全览 前言 得物App作为中国领先的潮流电商与鉴别平台&#xff0c;持续推动商品识别、真假鉴别、图像搜索、内容审核、智能推荐等视觉AI技术的创新与落地。得物视觉算法岗位…

[Linux入门] Linux 账号和权限管理入门:从基础到实践

一、Linux 用户账号&#xff1a;谁能访问系统&#xff1f; 1️⃣超级用户&#xff08;root&#xff09; 2️⃣普通用户 3️⃣程序用户 二、组账号&#xff1a;让用户管理更高效 1️⃣组的类型 2️⃣特殊组 三、用户与组的 “身份证”&#xff1a;UID 和 GID 四、配置文…

阿里云ssl证书自动安装及续订(acme)

目录 一、shell命令安装 二、docker run安装 三、docker compose安装 一、shell命令安装 # 安装acme curl https://get.acme.sh | sh -s emailfloxxx5163.com# 注册zerossl .acme.sh/acme.sh --register-account -m flowxxx25163.com --server zerossl# 获取证书 export Al…

@fullcalendar/vue 日历组件

功能&#xff1a;日程安排&#xff0c;展示日历&#xff0c;可以用来做会议日历&#xff0c;可以跨日期显示日程。 Fullcalendarvue3 日历组件 参考文档&#xff1a;【vue2】一个完整的日历组件 fullcalendar&#xff0c;会议预约功能 中文说明文档&#xff1a;https://www.he…

Dijkstra 算法求解多种操作

一、问题背景与核心需求 需要找到从a到b的最优操作序列&#xff0c;使得总花费最小。三种操作的规则为&#xff1a; 操作 1&#xff1a;x → x1&#xff0c;花费c1&#xff1b;操作 2&#xff1a;x → x-1&#xff0c;花费c2&#xff1b;操作 3&#xff1a;x → x*2&#xff0…

本地项目提交到git教程

创建远程仓库 登录 GitHub&#xff0c;点击右上角 New repository。 填写仓库名称&#xff08;如 my-project&#xff09;、描述&#xff0c;选择公开 / 私有。 不要初始化 README、.gitignore 或 LICENSE&#xff08;保持空仓库&#xff09;&#xff0c;点击 Create repositor…

Linux 密码生成利器:pwgen 命令详解

往期好文&#xff1a;统信 UOS 运行 Windows 应用新利器&#xff01;彩虹虚拟化软件 V3.2 全新上线&#xff0c;限时30天免费体验 在日常运维、安全测试、用户管理等场景中&#xff0c;随机密码的生成是一项常见需求。为了避免人工设置密码带来的重复性弱密码问题&#xff0c;…

Qt 应用程序入口代码分析

Qt 应用程序入口代码分析 这段代码是 Qt GUI 应用程序的标准入口点&#xff0c;相当于 Qt 程序的"心脏"。让我详细解释每一部分的作用&#xff1a; int main(int argc, char *argv[]) {// 1. 创建 Qt 应用程序对象QApplication a(argc, argv);// 2. 创建主窗口对象Wi…