原理说明

在对服务器进行维护时,有时也遇到由于系统 CPU(利用率)负载过高导致业务中断的情况。服务器上可能运行多个进程,查看单个进程的 CPU 都是正常的,但是整个系统的 CPU 负载可能是异常的。通过脚本对系统 CPU 负载进行时时监控,可以在异常时及时发送告警,便于维护人员及时处理,预防事故发生。下面的函数可以检测系统 CPU 使用情况 。使用 vmstat 取 5 次系统 CPU 的 idle 值,取平均值,然后通过与 100 取差得到当前 CPU 的实际占用值。
vmstat(VirtualMeomoryStatistics,虚拟内存统计)是Linux中监控内存的常用工具,可对操作系统的虚拟内存、进程、CPU等的整体情况进行监视。该命令可以显示关于系统各种资源之间相关性能的简要信息,这里我主要用它来看CPU的一个负载情况。

[root@host ~]# cat cpuload.sh 
#!/bin/bash
#Author: Jaking
#Mail: Jaking1024@163.com
#Date:2018/7/11
#Function:This script is to get the CPU load. 

function GetSysCPU 
 {
   CpuIdle=`vmstat 1 5 |sed -n '3,$p' | awk '{x = x + $15} END {print x/5}' | awk -F. '{print $1}'` 
   CpuNum=`echo "100-$CpuIdle" | bc` 
   echo $CpuNum 
 }

cpu=`GetSysCPU` 

 echo "The system CPU is $cpu"

 if [ $cpu -gt 80 ] 
 then 
 { 
    echo "The usage of system CPU is larger than 80%"
 } 
 else 
 { 
    echo "The usage of system CPU is normal"
 } 
 fi
[root@host ~]# bash cpuload.sh 
The system CPU is 8
The usage of system CPU is normal

从上面的输出可见:当前 Linux 服务器系统 CPU 利用率为 8%,是正常的,没有超过 80% 的告警限制。

原文来自:https://www.jianshu.com/p/8a67b4ee87a4

本文地址:https://www.linuxprobe.com/cpu-load-procedures.html编辑:public,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/