监控内存使用率脚本

2022/4/22 7:15:12

本文主要是介绍监控内存使用率脚本,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

案例需求

打印内存使用率脚本,打印内存使用率、swap使用率、buff&cache使用量

实现效果

 

例1:

 

 

 

 

 

例2:

内存使用率: 2.69%,buff&cache:535 MB
Swap使用率: 0%


 

 

脚本应用场景:

监控平台+内存监控脚本

手动监控

解决问题

随时掌握业务对内存的占用,合理使用内存资源

脚本思路

1、获取物理内存、swap的相关数据

​ 1.1通过数据检索获得物理内存总量、Swap的总量

​ 1.2通过数据检索获得物理内存的使用量,Swap的使用量

​ 1.3通过检索获得物理内存buff&cache的量

2、调用相关数据进行运算,并输出结果

 

监控命令

 

free

cat /proc/meminfo

 

实现代码

例1:

 

#! /bin/bash

#内存使用率统计脚本

# /proc/meminfo

#内存申请顺序 free-cache-buffer-swap

memory_use(){

memory_used=`head -2 /proc/meminfo |awk 'NR==1{t=$2}NR==2{f=$2;print(t-f)/t*100"%"}'`
memory_cache=`head -5 /proc/meminfo |awk 'NR==1{t=$2}NR==5{c=$2;print c*100/t"%"}'`
memory_buffer=`head -4 /proc/meminfo |awk 'NR==1{t=$2}NR==4{b=$2;print b*100/t"%"}'`

echo -e "memory_used:$memory_used\t buffer:$memory_buffer\t cached:$memory_cache"

}

memory_use

 

例2:

#!/bin/bash

#Created Time: 
#Release: 
#Description:内存使用率计算脚本

#1、通过free命令结合数据处理获得对应数据
#1.1、获得内存总量
memory_totle=`free -m|grep -i "mem"|tr -s " "|cut -d " " -f2`
swap_totle=`free -m|grep -i "swap"|tr -s " "|cut -d " " -f2`
#1.2、获得内存使用的量
memory_use=`free -m|grep -i "mem"|tr -s " "|cut -d " " -f3`
swap_use=`free -m|grep -i "swap"|tr -s " "|cut -d " " -f3`
#1.3、buff/cache
buff_cache=`free -m|grep -i "mem"|tr -s " "|cut -d " " -f6`

#2、计算输出
#运算的时候是否需要小数点 浮点运算,要考虑使用的命令 (难点 重点)
#echo "内存使用率: $((memory_use*100/memory_totle))%"
#难点:浮点运算中,同优先级的情况下,大数除以小数 尽可能保证精确
echo "内存使用率: `echo "scale=2;$memory_use*100/$memory_totle"|bc`%,buff&cache:$buff_cache MB"
echo "Swap使用率: `echo "scale=2;$swap_use*100/$swap_totle"|bc`%"

 



这篇关于监控内存使用率脚本的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程