ubuntu

ubuntu cpustat如何集成到监控系统

小樊
48
2025-11-06 10:18:57
栏目: 智能运维

要将 cpustat 集成到监控系统中,您可以使用以下几种方法:

1. 使用脚本定期收集数据并发送到监控系统

您可以编写一个简单的 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,可以将上述脚本的输出保存到一个文件中,并配置 Prometheus 抓取该文件。

  1. 创建一个文件 /etc/prometheus/node_exporter/cpu_usage.conf,内容如下:

    scrape_configs:
      - job_name: 'node_cpu'
        static_configs:
          - targets: ['<your_node_ip>:<port>']
            labels:
              host: <your_hostname>
    
  2. 修改 Prometheus 配置文件 /etc/prometheus/prometheus.yml,添加抓取任务:

    scrape_configs:
      - job_name: 'node_cpu'
        static_configs:
          - targets: ['<your_node_ip>:<port>']
            labels:
              host: <your_hostname>
    
  3. 重启 Prometheus 服务:

    sudo systemctl restart prometheus
    

2. 使用现有监控工具

许多现有的监控工具已经支持 cpustat 或类似的命令行工具。例如:

示例:使用 Nagios 和 NRPE

  1. 在 Nagios 服务器上安装 NRPE:

    sudo apt-get install nagios-nrpe-server nagios-plugins
    
  2. 在远程节点上配置 NRPE:

    编辑 /etc/nagios/nrpe.cfg 文件,添加以下内容:

    command[check_cpu]=/usr/lib/nagios/plugins/check_nrpe -H $HOSTADDRESS$ -c check_cpu
    
  3. 创建一个 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
    
  4. 赋予脚本执行权限:

    sudo chmod +x /usr/lib/nagios/plugins/check_cpu
    
  5. 在 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
    }
    
  6. 重启 Nagios 服务:

    sudo systemctl restart nagios
    

通过以上步骤,您可以将 cpustat 集成到您的监控系统中,并实时监控 CPU 使用率。

0
看了该问题的人还看了