Python搭建香港VPS监控面板:Grafana+Prometheus实战
文章分类:行业新闻 /
创建时间:2025-11-03
Python搭建香港VPS监控面板:Grafana+Prometheus实战
你有一台香港VPS,像拥有一座远程数字城堡,却总担心里面的“居民”——CPU、内存、磁盘等系统资源是否安好?想随时看到它们的状态?用Python结合Grafana和Prometheus就能搭建一套实时可视化监控面板,让VPS运行情况一目了然。
核心工具:Prometheus与Grafana
Prometheus是开源监控警报工具包,像不知疲倦的哨兵,定时从目标(比如你的香港VPS)抓取CPU使用率、内存占用等指标数据,存进本地时间序列数据库。Grafana则是强大的可视化工具,像技艺精湛的画师,能把Prometheus收集的枯燥数据,变成折线图、柱状图等直观图表,让你一眼看清VPS运行状态。
环境准备:基础配置要到位
开始前先检查香港VPS环境:确保已安装Python(建议3.6以上版本),并拥有root权限。同时需开放两个关键端口——Prometheus默认9090端口、Grafana默认3000端口,后续访问和数据传输都要用到。
安装Prometheus:数据采集第一步
在香港VPS上执行以下命令安装Prometheus:
wget https://github.com/prometheus/prometheus/releases/download/v2.35.0/prometheus-2.35.0.linux-amd64.tar.gz
tar xvf prometheus-2.35.0.linux-amd64.tar.gz
cd prometheus-2.35.0.linux-amd64
安装完成后需配置监控目标。编辑`prometheus.yml`文件,添加对香港VPS的监控配置:
scrape_configs:
- job_name: 'vps_monitoring'
static_configs:
- targets: ['localhost:9100']
这里的9100端口是Node Exporter(用于收集系统指标的组件)的默认端口。最后启动Prometheus服务:
./prometheus --config.file=prometheus.yml
安装Node Exporter:系统指标收集器
Node Exporter是Prometheus的“得力助手”,专门负责收集VPS的CPU、内存、磁盘等硬件指标。通过以下命令安装:
wget https://github.com/prometheus/node_exporter/releases/download/v1.3.1/node_exporter-1.3.1.linux-amd64.tar.gz
tar xvf node_exporter-1.3.1.linux-amd64.tar.gz
cd node_exporter-1.3.1.linux-amd64
安装后直接启动即可:
./node_exporter
安装Grafana:数据可视化引擎
在香港VPS上安装Grafana,需先添加软件源并更新包列表:
sudo apt-get install -y apt-transport-https software-properties-common
wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add -
echo "deb https://packages.grafana.com/oss/deb stable main" | sudo tee -a /etc/apt/sources.list.d/grafana.list
sudo apt-get update
sudo apt-get install grafana
安装完成后启动并设置开机自启:
sudo systemctl start grafana-server
sudo systemctl enable grafana-server
配置Grafana:打造专属监控看板
打开浏览器访问`http://你的VPS公网IP:3000`,用默认账号(admin/admin)登录Grafana。首先添加Prometheus作为数据源:在“Configuration”菜单选择“Data Sources”,输入Prometheus地址(如`http://localhost:9090`)完成配置。
接着创建监控仪表盘:点击“Create”选择“Dashboard”,添加图表时从“Metrics”中选择Prometheus提供的指标(如`node_cpu_seconds_total`监控CPU使用率、`node_memory_MemFree_bytes`监控可用内存)。调整图表类型、时间范围等参数,就能得到一套个性化的香港VPS监控看板。
Python扩展:自定义业务指标监控
如果需要监控业务相关的自定义指标(比如接口调用次数、订单处理量),可以用Python编写脚本扩展功能。以下是一个简单示例:
from prometheus_client import start_http_server, Gauge
import time
# 定义自定义指标:业务处理成功率
business_success_rate = Gauge('business_success_rate', '业务处理成功率(0-100)')
def collect_data():
# 这里替换为实际业务数据获取逻辑,示例返回固定值
business_success_rate.set(95)
if __name__ == '__main__':
# 启动HTTP服务器暴露指标,供Prometheus抓取
start_http_server(8000)
while True:
collect_data()
time.sleep(10) # 每10秒更新一次数据
将脚本保存为`custom_metric.py`并运行:
python custom_metric.py
最后在Prometheus的`prometheus.yml`中添加对该脚本的抓取配置:
scrape_configs:
- job_name: 'custom_metric'
static_configs:
- targets: ['localhost:8000']
通过这套方案,你不仅能监控香港VPS的基础资源状态,还能结合Python扩展业务指标监控,真正实现对数字资产的全方位守护。
工信部备案:苏ICP备2025168537号-1