要将 cpustat 集成到监控系统中,您可以使用以下几种方法:
您可以编写一个简单的 Bash 脚本,使用 cpustat 收集 CPU 使用率数据,并将其发送到您选择的监控系统(如 Prometheus、Grafana、InfluxDB 等)。
#!/bin/bash
# 收集 CPU 统计信息
cpu_stats=$(cpustat -c 1 1)
# 解析输出
user=$(echo "$cpu_stats" | awk '{print $2}')
system=$(echo "$cpu_stats" | awk '{print $4}')
idle=$(echo "$cpu_stats" | awk '{print $5}')
# 计算 CPU 使用率
total_idle=$(echo "$idle + $iowait" | bc)
total_time=$(echo "100 - $total_idle" | bc)
# 格式化输出为 Prometheus 指标格式
echo "cpu_usage_user{host=$(hostname)} $user"
echo "cpu_usage_system{host=$(hostname)} $system"
echo "cpu_usage_idle{host=$(hostname)} $total_idle"
如果您使用的是 Prometheus,可以将上述脚本的输出保存到一个文件中,并配置 Prometheus 抓取该文件。
创建一个文件 /etc/prometheus/node_exporter/cpu_usage.conf,内容如下:
scrape_configs:
- job_name: 'node_cpu'
static_configs:
- targets: ['<your_node_ip>:<port>']
labels:
host: <your_hostname>
修改 Prometheus 配置文件 /etc/prometheus/prometheus.yml,添加抓取任务:
scrape_configs:
- job_name: 'node_cpu'
static_configs:
- targets: ['<your_node_ip>:<port>']
labels:
host: <your_hostname>
重启 Prometheus 服务:
sudo systemctl restart prometheus
许多现有的监控工具已经支持 cpustat 或类似的命令行工具。例如:
cpustat 并将结果发送回 Nagios 服务器。cpustat 并将结果发送回 Zabbix 服务器。在 Nagios 服务器上安装 NRPE:
sudo apt-get install nagios-nrpe-server nagios-plugins
在远程节点上配置 NRPE:
编辑 /etc/nagios/nrpe.cfg 文件,添加以下内容:
command[check_cpu]=/usr/lib/nagios/plugins/check_nrpe -H $HOSTADDRESS$ -c check_cpu
创建一个 NRPE 插件脚本 /usr/lib/nagios/plugins/check_cpu:
#!/bin/bash
# 运行 cpustat 并解析输出
cpu_stats=$(cpustat -c 1 1)
user=$(echo "$cpu_stats" | awk '{print $2}')
system=$(echo "$cpu_stats" | awk '{print $4}')
idle=$(echo "$cpu_stats" | awk '{print $5}')
# 计算 CPU 使用率
total_idle=$(echo "$idle" | bc)
total_time=100
usage=$(echo "scale=2; ($total_time - $total_idle) / $total_time * 100" | bc)
# 检查 CPU 使用率是否超过阈值
if (( $(echo "$usage > 80" | bc) )); then
echo "CRITICAL - CPU usage is $usage%"
exit 2
elif (( $(echo "$usage > 50" | bc) )); then
echo "WARNING - CPU usage is $usage%"
exit 1
else
echo "OK - CPU usage is $usage%"
exit 0
fi
赋予脚本执行权限:
sudo chmod +x /usr/lib/nagios/plugins/check_cpu
在 Nagios 服务器上配置主机和服务:
编辑 /etc/nagios/nagios.cfg 文件,添加远程节点的主机定义和服务定义:
define host {
use generic-host
host_name <remote_node_ip>
alias <remote_node_hostname>
}
define service {
use generic-service
host_name <remote_node_ip>
service_description CPU Usage
check_command check_cpu
}
重启 Nagios 服务:
sudo systemctl restart nagios
通过以上步骤,您可以将 cpustat 集成到您的监控系统中,并实时监控 CPU 使用率。