强曰为道

与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

第9章:Glances详解

第9章:Glances详解

9.1 Glances概述

什么是Glances

Glances 是一款跨平台的系统监控工具,使用Python编写,提供全面的系统监控功能,包括CPU、内存、磁盘、网络、传感器、进程等。

Glances的特点

  1. 全面监控 - CPU、内存、磁盘、网络、传感器、进程全覆盖
  2. Web界面 - 内置Web服务器,支持浏览器访问
  3. API接口 - RESTful API,便于集成
  4. 告警功能 - 内置告警系统,可配置阈值
  5. 数据导出 - 支持CSV、JSON、Prometheus等格式
  6. 插件系统 - 可扩展的插件架构
  7. 跨平台 - 支持Linux、macOS、Windows

Glances vs 其他工具

特性Glanceshtopatopbtop
全面监控有限
Web界面
API支持
告警功能
数据导出有限
插件系统
资源占用中等中等

9.2 安装与配置

安装方法

# 方法1:pip安装(推荐)
pip install glances

# 方法2:pip3安装
pip3 install glances

# 方法3:带Web界面
pip install 'glances[web]'

# 方法4:带所有功能
pip install 'glances[all]'

# Debian/Ubuntu
sudo apt install glances

# CentOS/RHEL
sudo yum install epel-release
sudo yum install glances

# Arch Linux
sudo pacman -S glances

# macOS
brew install glances

# Docker
docker run -d --name glances \
  --pid=host \
  --privileged \
  -p 61208:61208 \
  -v /var/run/docker.sock:/var/run/docker.sock:ro \
  nicolargo/glances

验证安装

glances --version
# Glances v3.4.0

Web界面安装

# 安装Web依赖
pip install 'glances[web]'

# 或者单独安装
pip install bottle
pip install requests

配置文件

# 配置文件位置
~/.config/glances/glances.conf

# 系统配置
/etc/glances/glances.conf

# 创建配置目录
mkdir -p ~/.config/glances

# 首次运行会自动生成默认配置
glances

9.3 基本使用

启动方式

# 基本启动
glances

# Web模式
glances -w

# 服务器模式
glances -s

# 客户端模式
glances -c <server_ip>

# 安静模式(无颜色)
glances --quiet

# 刷新间隔
glances -t 5

界面解读

┌────────────────────────────────────────────────────────────────────────────┐
│ server1 (Linux 5.15.0-58-generic) - 2026-05-10 14:32:15                    │
├────────────────────────────────────────────────────────────────────────────┤
│ CPU    [5.2%]   MEM    [62.5%]   SWAP   [0.0%]   LOAD    2-core          │
│ user: 3.2%      total: 16.0G     total: 8.0G     1 min: 0.52             │
│ system: 1.5%    used: 10.0G      used: 0.0B      5 min: 0.58             │
│ idle: 94.8%     free: 6.0G       free: 8.0G      15 min: 0.59            │
├────────────────────────────────────────────────────────────────────────────┤
│ NETWORK    Rx/s    Tx/s   TASKS   215 (215 thr, 2 run)                    │
│ eth0       1.2M    456K           procs: 215                              │
│ lo           0B      0B           running: 2                              │
│                                sleeping: 213                               │
├────────────────────────────────────────────────────────────────────────────┤
│ DISK I/O    R/s     W/s    FILE SYS     Used    Total                    │
│ sda        1.2M    456K   /            45.2G    100G                      │
│ sdb        234K    123K   /home        23.4G     50G                      │
├────────────────────────────────────────────────────────────────────────────┤
│ PROCESS   CPU%   MEM%   USER    PID    TIME    NAME                      │
│ nginx     45.2   12.3   root   1234   1:23:45   nginx                    │
│ mysqld    23.1   34.5   mysql  5678   12:34:56   mysqld                   │
└────────────────────────────────────────────────────────────────────────────┘

面板说明

面板显示内容
CPUCPU使用率、用户/系统/空闲
MEM内存使用、总量/已用/空闲
SWAP交换分区使用
LOAD系统负载(1/5/15分钟)
NETWORK网络接口流量
DISK I/O磁盘IO读写
FILE SYS文件系统使用
PROCESS进程列表

9.4 交互命令

导航命令

按键功能
1切换CPU显示模式
a自动排序
A禁用/启用警告
c按CPU排序
d显示/隐藏磁盘IO
D显示/隐藏Docker
e显示/隐藏进程扩展信息
f显示/隐藏文件系统
g生成历史图表
h显示帮助
i按IO排序
I显示/隐藏IP
l显示/隐藏日志
m按内存排序
M重置进程摘要
n显示/隐藏网络
N显示/隐藏网络连接
p按进程名排序
P显示/隐藏进程
q退出
r重置历史
s显示/隐藏传感器
S显示/隐藏RAID
t按CPU时间排序
T累积进程时间
u按用户排序
U显示累积网络
w删除警告日志
x删除警告和进程
z显示/隐藏进程列表
0显示/隐藏IRQ
1切换CPU显示
2显示/隐藏左侧边栏
3显示/隐藏右侧边栏
/切换进程路径显示

排序命令

按键功能
c按CPU%排序
m按MEM%排序
i按IO排序
p按进程名排序
t按CPU时间排序
u按用户排序

进程操作

按键功能
Enter选择进程
k杀死进程
e扩展进程信息

9.5 Web界面

启动Web服务

# 启动Web模式
glances -w

# 指定端口
glances -w -p 61208

# 绑定所有接口
glances -w --bind 0.0.0.0

# 指定刷新间隔
glances -w -t 5

# 带密码保护
glances -w --username --password

访问Web界面

# 本地访问
http://localhost:61208

# 远程访问
http://server_ip:61208

# RESTful API
http://server_ip:61208/api/4/cpu
http://server_ip:61208/api/4/mem
http://server_ip:61208/api/4/net

Web界面功能

URL功能
/主监控界面
/api/4/API根路径
/api/4/cpuCPU数据
/api/4/mem内存数据
/api/4/net网络数据
/api/4/diskio磁盘IO数据
/api/4/fs文件系统数据
/api/4/processlist进程列表
/api/4/alert告警信息

Web界面配置

# ~/.config/glances/glances.conf

[webserver]
# 绑定地址
bind=0.0.0.0
# 端口
port=61208
# 用户名
username=admin
# 密码
password=secret
# 刷新间隔(毫秒)
refresh=5000

9.6 API接口

RESTful API

启动API服务

glances -w

API端点

# CPU信息
curl http://localhost:61208/api/4/cpu

# 内存信息
curl http://localhost:61208/api/4/mem

# 网络信息
curl http://localhost:61208/api/4/net

# 磁盘IO
curl http://localhost:61208/api/4/diskio

# 文件系统
curl http://localhost:61208/api/4/fs

# 进程列表
curl http://localhost:61208/api/4/processlist

# 系统信息
curl http://localhost:61208/api/4/system

# 所有数据
curl http://localhost:61208/api/4/all

API响应格式

CPU数据

{
  "total": 5.2,
  "user": 3.2,
  "system": 1.5,
  "idle": 94.8,
  "iowait": 0.3,
  "steal": 0.0
}

内存数据

{
  "total": 17179869184,
  "available": 6442450944,
  "percent": 62.5,
  "used": 10737418240,
  "free": 6442450944,
  "active": 8589934592,
  "inactive": 4294967296,
  "buffers": 536870912,
  "cached": 4294967296
}

API集成示例

Python示例

import requests
import json

def get_glances_data(host='localhost', port=61208):
    """获取Glances监控数据"""
    base_url = f"http://{host}:{port}/api/4"
    
    data = {}
    
    # CPU
    resp = requests.get(f"{base_url}/cpu")
    data['cpu'] = resp.json()
    
    # 内存
    resp = requests.get(f"{base_url}/mem")
    data['memory'] = resp.json()
    
    # 网络
    resp = requests.get(f"{base_url}/net")
    data['network'] = resp.json()
    
    return data

# 使用
data = get_glances_data()
print(f"CPU使用率: {data['cpu']['total']}%")
print(f"内存使用率: {data['memory']['percent']}%")

Shell脚本示例

#!/bin/bash
# glances_monitor.sh

API_URL="http://localhost:61208/api/4"

# 获取CPU使用率
CPU=$(curl -s $API_URL/cpu | jq '.total')

# 获取内存使用率
MEM=$(curl -s $API_URL/mem | jq '.percent')

echo "CPU: ${CPU}%"
echo "Memory: ${MEM}%"

9.7 告警设置

配置文件

# ~/.config/glances/glances.conf

[cpu]
# CPU警告阈值
careful=50
warning=70
critical=90

[memory]
# 内存警告阈值
careful=50
warning=70
critical=90

[swap]
# Swap警告阈值
careful=50
warning=70
critical=90

[load]
# 负载警告阈值(基于CPU核心数)
careful=1.0
warning=2.0
critical=4.0

[filesystem]
# 文件系统使用率阈值
careful=50
warning=70
critical=90

[temperature]
# 温度阈值(摄氏度)
careful=60
warning=70
critical=80

[network]
# 网络带宽阈值(字节/秒)
careful=500000000
warning=700000000
critical=900000000

告警级别

级别颜色含义
OK绿色正常
CAREFUL蓝色注意
WARNING黄色警告
CRITICAL红色严重

告警动作

# ~/.config/glances/glances.conf

[outputs]
# 告警输出到文件
file=/var/log/glances/alerts.log

# 告警输出到CSV
csv=/var/log/glances/alerts.csv

# 告警输出到Prometheus
prometheus_host=0.0.0.0
prometheus_port=9091

自定义告警脚本

#!/bin/bash
# glances_alert.sh

# 监控并发送告警
while true; do
    # 获取CPU使用率
    CPU=$(curl -s http://localhost:61208/api/4/cpu | jq '.total')
    
    # 检查阈值
    if (( $(echo "$CPU > 90" | bc -l) )); then
        echo "CRITICAL: CPU使用率 ${CPU}%" | mail -s "CPU告警" [email protected]
    elif (( $(echo "$CPU > 70" | bc -l) )); then
        echo "WARNING: CPU使用率 ${CPU}%" | mail -s "CPU警告" [email protected]
    fi
    
    sleep 60
done

9.8 数据导出

CSV导出

# 导出为CSV
glances --export csv --export-csv-file /tmp/glances.csv

# 指定时间间隔
glances --export csv --export-csv-file /tmp/glances.csv -t 10

JSON导出

# 导出为JSON
glances --export json --export-json-file /tmp/glances.json

# 单次输出
glances --export json --stdout

Prometheus导出

# 启动Prometheus导出器
glances --export prometheus

# Prometheus配置
# scrape_configs:
#   - job_name: 'glances'
#     static_configs:
#       - targets: ['localhost:9091']

InfluxDB导出

# ~/.config/glances/glances.conf

[influxdb2]
# InfluxDB配置
host=localhost
port=8086
protocol=http
org=myorg
bucket=glances
token=mytoken
# 启动InfluxDB导出
glances --export influxdb2

ElasticSearch导出

# ~/.config/glances/glances.conf

[elasticsearch]
# ElasticSearch配置
host=localhost
port=9200
index=glances
# 启动ElasticSearch导出
glances --export elasticsearch

9.9 插件系统

插件目录

# 系统插件
/usr/lib/python3/dist-packages/glances/plugins/

# 用户插件
~/.config/glances/plugins/

内置插件列表

插件功能
cpuCPU监控
mem内存监控
diskio磁盘IO监控
network网络监控
fs文件系统监控
sensors传感器监控
processcount进程计数
processlist进程列表
ipIP地址监控
dockerDocker监控
gpuGPU监控
irq中断监控
folders文件夹监控
raidRAID监控

启用/禁用插件

# ~/.config/glances/glances.conf

[cpu]
disable=False

[mem]
disable=False

[docker]
disable=False

[gpu]
disable=False

# 禁用某个插件
[folders]
disable=True

自定义文件夹监控

# ~/.config/glances/glances.conf

[folders]
# 监控文件夹大小
folder_1_path=/var/log
folder_1_careful=500000000
folder_1_warning=700000000
folder_1_critical=900000000

folder_2_path=/tmp
folder_2_careful=1000000000
folder_2_warning=2000000000
folder_2_critical=3000000000

9.10 Docker监控

启用Docker监控

# 确保Docker socket可访问
ls -la /var/run/docker.sock

# 启动Glances时挂载Docker socket
docker run -d --name glances \
  --pid=host \
  --privileged \
  -p 61208:61208 \
  -v /var/run/docker.sock:/var/run/docker.sock:ro \
  nicolargo/glances

Docker配置

# ~/.config/glances/glances.conf

[docker]
# Docker监控配置
disable=False
# 刷新间隔
refresh=60
# 显示所有容器
allcontainers=False

Docker API

# 获取Docker容器信息
curl http://localhost:61208/api/4/docker

# 获取特定容器
curl http://localhost:61208/api/4/docker/<container_id>

9.11 服务器模式

服务器端配置

# 启动服务器模式
glances -s

# 指定端口
glances -s -p 61209

# 绑定所有接口
glances -s --bind 0.0.0.0

# 带密码保护
glances -s --username admin --password secret

客户端连接

# 连接到服务器
glances -c server_ip

# 指定端口
glances -c server_ip:61209

# 带认证
glances -c server_ip --username admin --password secret

服务器配置

# ~/.config/glances/glances.conf

[outputs]
# 服务器配置
server_listen=0.0.0.0
server_port=61209

# 认证
username=admin
password=secret

9.12 高级配置

完整配置示例

# ~/.config/glances/glances.conf

[global]
# 全局刷新间隔(秒)
refresh=2

[cpu]
# CPU警告阈值
careful=50
warning=70
critical=90
# 显示每核CPU
percpu=True

[memory]
# 内存警告阈值
careful=50
warning=70
critical=90

[swap]
# Swap警告阈值
careful=25
warning=50
critical=75

[load]
# 负载警告阈值
careful=1.0
warning=2.0
critical=4.0

[filesystem]
# 文件系统使用率阈值
careful=50
warning=70
critical=90
# 忽略的文件系统
ignore=/snap,/boot/efi

[temperature]
# 温度阈值
careful=60
warning=70
critical=80

[network]
# 网络阈值(字节/秒)
careful=500000000
warning=700000000
critical=900000000
# 忽略的接口
ignore=lo,docker0

[ip]
# IP地址配置
public_only=False
public_dns_server=8.8.8.8

[docker]
# Docker配置
disable=False
refresh=60

[webserver]
# Web服务器配置
bind=0.0.0.0
port=61208
username=
password=
refresh=5000

9.13 实战场景

场景1:统一监控平台

需求:监控多台服务器

# 服务器端(监控节点)
glances -s --bind 0.0.0.0 -p 61209

# 客户端(被监控节点)
# 安装Glances后自动收集数据

# 访问Web界面
http://monitor_server:61208

场景2:性能数据采集

需求:采集性能数据用于分析

# 采集数据到CSV
glances --export csv --export-csv-file /var/log/glances/$(date +%Y%m%d).csv -t 10

# 采集数据到JSON
glances --export json --export-json-file /var/log/glances/$(date +%Y%m%d).json -t 10

场景3:Prometheus + Grafana

需求:集成Prometheus监控

# 启动Prometheus导出
glances --export prometheus

# Prometheus配置
cat >> /etc/prometheus/prometheus.yml << EOF
  - job_name: 'glances'
    static_configs:
      - targets: ['server1:9091', 'server2:9091']
EOF

# Grafana导入Dashboard
# 使用Dashboard ID: 1234

场景4:告警通知

需求:CPU超阈值时发送告警

#!/bin/bash
# glances_alert.sh

ALERT_FILE="/tmp/glances_alerts.log"

# 检查CPU
CPU=$(curl -s http://localhost:61208/api/4/cpu | jq '.total')
if (( $(echo "$CPU > 90" | bc -l) )); then
    echo "$(date): CRITICAL CPU ${CPU}%" >> $ALERT_FILE
    # 发送通知
    curl -X POST -H 'Content-type: application/json' \
        --data "{\"text\":\"CRITICAL: CPU ${CPU}%\"}" \
        https://hooks.slack.com/services/xxx
fi

场景5:容器监控

需求:监控Docker容器资源

# 使用Docker启动Glances
docker run -d --name glances \
  --pid=host \
  --privileged \
  -p 61208:61208 \
  -v /var/run/docker.sock:/var/run/docker.sock:ro \
  -v /path/to/glances.conf:/etc/glances/glances.conf:ro \
  nicolargo/glances

# 访问Docker面板
# 按D显示/隐藏Docker面板

场景6:远程服务器监控

需求:监控远程服务器

# 远程服务器启动服务
ssh user@server "glances -s --bind 0.0.0.0"

# 本地连接
glances -c server_ip

# 或通过Web访问
# http://server_ip:61208

9.14 性能开销

模式CPU占用内存占用网络开销
终端模式1-3%50-100MB
Web模式2-5%100-200MB
服务器模式2-5%100-200MB中等
导出模式3-6%100-200MB取决于目标

优化建议

# 增加刷新间隔
glances -t 10

# 禁用不需要的插件
# 编辑配置文件禁用

# 使用Docker运行(隔离资源)
docker run --memory=256m --cpus=0.5 ...

9.15 故障排查

问题1:Web界面无法访问

# 检查端口是否监听
ss -tuln | grep 61208

# 检查防火墙
sudo iptables -L -n

# 绑定所有接口
glances -w --bind 0.0.0.0

问题2:API返回错误

# 检查Glances是否运行
ps aux | grep glances

# 测试API
curl http://localhost:61208/api/4/version

# 查看日志
tail -f ~/.config/glances/glances.log

问题3:Docker监控不工作

# 检查Docker socket权限
ls -la /var/run/docker.sock

# 确保挂载正确
docker run -v /var/run/docker.sock:/var/run/docker.sock:ro ...

# 检查用户组
groups
sudo usermod -aG docker $USER

问题4:内存占用过高

# 增加刷新间隔
glances -t 30

# 禁用历史数据
# 编辑配置

# 重启Glances

9.16 扩展阅读

9.17 快速参考

常用命令

# 基本启动
glances

# Web模式
glances -w

# 服务器模式
glances -s

# 客户端连接
glances -c server_ip

# 导出CSV
glances --export csv --export-csv-file output.csv

# 导出JSON
glances --export json --export-json-file output.json

# 刷新间隔
glances -t 5

# 安静模式
glances --quiet

常用交互键

┌────────────────────────────────────────────────┐
│           Glances 快捷键速查卡                  │
├────────────────────────────────────────────────┤
│  显示控制      │  排序          │  功能         │
│  1  CPU模式    │  c  按CPU     │  q  退出      │
│  d  磁盘IO     │  m  按内存    │  h  帮助      │
│  n  网络       │  i  按IO      │  A  告警      │
│  f  文件系统   │  p  按进程名  │  E  扩展信息  │
│  s  传感器     │  u  按用户    │  /  进程路径  │
│  D  Docker     │  t  按时间    │  2  左侧边栏  │
└────────────────────────────────────────────────┘

9.18 本章小结

本章详细介绍了Glances的使用:

  1. 安装配置: 多种安装方式、配置文件详解
  2. 基本使用: 终端模式、界面解读
  3. 交互命令: 显示控制、排序、进程操作
  4. Web界面: 浏览器访问、远程监控
  5. API接口: RESTful API、集成示例
  6. 告警设置: 阈值配置、告警级别
  7. 数据导出: CSV、JSON、Prometheus、InfluxDB
  8. 插件系统: 内置插件、自定义配置
  9. Docker监控: 容器资源监控
  10. 服务器模式: 多服务器统一监控

Glances是功能最全面的系统监控工具之一,特别适合需要统一监控、API集成的场景。


上一章: 第8章:vmstat/iostat/SAR 下一章: 第10章:dstat与nmon