python flusk 監控

# 創建虛擬環境目錄 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…