Loading... ## 说明 用于监控树莓派/香橙派的温度 #### 运行环境 Python >= 3.6 ## 代码 pi_exporter.py ```python from prometheus_client import start_http_server, Gauge import time # 监听端口 EXPORTER_PORT = 9621 # 创建 Gauge 指标 pi_temperature = Gauge('pi_temperature', 'Pi Temperature in Celsius') def get_temperature(): # 读取温度数据 with open('/sys/class/thermal/thermal_zone0/temp', 'r') as file: temperature_raw = file.read().strip() # 将温度数据转换为摄氏度 temperature_celsius = float(temperature_raw) / 1000.0 return temperature_celsius if __name__ == '__main__': start_http_server(EXPORTER_PORT) # 启动 Prometheus Exporter 的 HTTP 服务器 print(f'Pi exporter started - {EXPORTER_PORT}') while True: temperature = get_temperature() pi_temperature.set(temperature) time.sleep(1) # 每秒更新一次指标的值 ``` ## 运行 创建目录,然后将 pi_exporter.py 放在 /usr/local/pi_exporter 目录下 ```bash mkdir /usr/local/pi_exporter ``` 安装依赖 ```bash pip3 install prometheus_client ``` 创建 systemd 服务 `vim /etc/systemd/system/pi_exporter.service`,如果路径不同,需要修改下对应的路径 ```bash [Unit] Description=Pi Exporter Service [Service] User=prometheus ExecStart=/usr/bin/python3 /usr/local/pi_exporter/pi_exporter.py Restart=on-failure RestartPreventExitStatus=23 RestartSec=3 [Install] WantedBy=multi-user.target ``` 启动服务 ```bash service pi_exporter start systemctl enable pi_exporter service pi_exporter status ``` 对 Prometheus Server 放行防火墙端口 ```bash iptables -A INPUT -s 10.20.30.0/24 -p tcp --dport 9621 -j ACCEPT -m comment --comment "prometheus-pi-exporter" ``` 访问 `http://IP:9621/metrics` 可看到指标 `pi_temperature`  ## 接入 Prometheus Server 修改 Prometheus 配置 `vim /usr/local/prometheus/prometheus.yml`,在 `scrape_configs` 中增加 Job 和 Targets ```yaml - job_name: "pi" static_configs: # Raspberry PI - targets: ["IP:9621"] # Orange PI - targets: ["IP:9621"] ``` 重载配置 `service prometheus reload`,可以看到对应的 Target 已经 up  查询指标   最后修改:2024 年 03 月 07 日 © 允许规范转载 赞 如果觉得我的文章对你有用,请随意赞赏