Shell script case (iii) accurately monitor CPU usage with the top command

Source: Internet
Author: User
Tags cpu usage

Requirements: accurately monitor CPU with top command

Preparation knowledge: Top use, basic awk, DC (default bash shell does not support decimal operations)

The script is as follows

[[email protected] scripts]# cat cpu.sh #!/bin/bash -# top -n 参数指定运行次数,1代表运行一次即停止,不再等待top数据更新,使用awk指定分割符,提取数据cpu_us=`top -n 1 | grep ‘Cpu(s)‘ | awk -F‘[" "%]+‘ ‘{print $2}‘`cpu_sy=`top -n 1 | grep ‘Cpu(s)‘ | awk -F‘[" "%]+‘ ‘{print $4}‘`cpu_idle=`top -n 1 | grep ‘Cpu(s)‘ | awk -F‘[" "%]+‘ ‘{print $8}‘`# 默认bash shell不能直接运算小数点,所以需要借助bc# bc命令是一种支持任意精度的交互执行的计算器语言。# 常见用法 echo "1.23*5" | bc cpu_sum=$(echo "$cpu_us+$cpu_sy"|bc)echo "CPU_SUM: $cpu_sum%"echo "CPU_Idle: ${cpu_idle}%"#超过阀值即发送邮件if [ $cpu_sum -ge 90 ];then        

Result of Operation

The script can be added to the scheduled task

This concludes.

Shell script case (iii) accurately monitor CPU usage with the top command

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.