Shell之監控cpu、內存、磁盤腳本


#!/bin/bash

#獲取內存情況

mem_total=`free | awk 'NR==2{print $2}'`  #獲取內存總大小
mem_use=`free  | awk 'NR==2{print $3}'`  #獲取內存使用大小

#統計內存使用率 (使用大小/總大小)

mem_use_rate=`awk 'BEGIN{print('$mem_use'/'mem_total')*100}'`

#echo $mem_use_rate

#獲取磁盤使用率
disk_use_rate=`df -h | grep /dev/vda1 | awk -F '[ %]+' '{print $5}'`

#echo $disk_use_rate

#獲取cpu使用率
cpu_use_rate=`top -n 1 | grep Cpu |awk '{print $2}'`

#echo $cpu_use_rate

#報警時間
file_log=/home/error.log  #提前創建
now_time=`date '+%F %T'`

function send_mail(){

        mail -s "監控報警"      *******@qq.com < /home/error.log
}

function check(){

        if [[ "men_use_rate" > 80 ]] || [[ "disk_use_rate" > 5 ]] || [[ "cpu_use_rate" > 50 ]];then   
                echo "報警時間:"$now_time > $file_log
                echo "cpu使用率:${cpu_use_rate}% --> 磁盤使用率:${disk_use_rate}% --> 內存使用率:${men_use_rate}"
                send_mail
        fi
}

function main(){
        check
}
main

操作系統:centos7.5     上面獲取的數據顯示34,相當於34%   報警部分可根據情況自己寫上面用的是sendmail(阿里雲服務器上有限制,鼓搗半天才發現需要開通,好像還收費,果斷放棄)

free

df -h

top -n 1 (top是實時監控,-n 1 顯示那一時刻的數據)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM