編寫shell腳本實現對虛擬機cpu、內存、磁盤監控機制

1、安裝Vmware,並經過鏡像安裝centos7。html

 

2、安裝xshell(能夠不裝,能夠直接在虛擬機中直接進行如下步驟)linux

 

3、安裝mailshell

  通常Linux發送報警郵件經過本地郵箱或外部郵箱服務器,這裏用最簡單的方法實現linux 使用外部郵箱便可實現發送郵件功能centos

  yum -y install mailxbash

  yum -y install sendmail服務器

 

如果安裝以後報錯,問題請參考:http://blog.sina.com.cn/s/blog_72682ca201017vxj.htmlcentos7

4、配置qq郵箱:spa

  • 得到受權碼
  • 修改發件人配置文件
  1. 經過命令:[root@192 shell_test]# vi /etc/mail.rc進入並在裏面設置發件人郵箱,第四行是受權碼
  2. set from=xxxx@qq.com
    set smtp=smtp.qq.com
    set smtp-auth-user=xxxx@qq.com
    set smtp-auth-password=fvihrgcgisiodjid
    set smtp-auth=login

4、編寫shell腳本3d

#!/bin/bash
#對cpu使用率進行獲取
cpuMonitor=`top -n 1 | awk -F '[ %]+' 'NR==3 {print $3}'`
#對磁盤使用率進行獲取
data_name="/dev/sda1"
diskMonitor=`df -h | grep $data_name | awk -F '[ %]+' '{print $5}'`
fileLog=/tmp/monitor.log
#獲取內存狀況
mem=`free -m | awk '{if(NR==2){print "Total Mem:" $2}else if(NR==3){print "Used Mem:" $3"\nFree Mem:" $4}}'`
mem_total=`free -m | awk -F '[ :]+' 'NR==2{print $2}'`
mem_used=`free -m | awk -F '[ :]+' 'NR==3{print $3}'`
#統計內存使用率
mem_used_persent=`awk 'BEGIN{printf "%.0f\n",('$mem_used'/'$mem_total')*100}'`
#獲取報警時間
now_time=`date '+%F %T'`
function send_mail(){
        mail -s "監控報警" xxx@qq.com < /tmp/monitor.log
}
function check(){
        if [[ "$cpuMonitor" >0.0000001 ]] || [[ "$diskMonitor" > 0.000000000000001 ]] || [[ "$mem_used_persent" >0.0000000000000001 ]];then
                echo "報警時間:${now_time}" > $fileLog
                echo -e  "CPU使用率:${cpuMonitor}% \n 磁盤使用率:${diskMonitor}% \n 內存使
用率:${mem_used_persent}%" >> $fileLog
                send_mail
        fi
}
function main(){
        check
}
main

  注意:code

  • 此時的郵箱地址爲收件人郵箱地址,
  • 重定向的用法(即追加與覆蓋)
  • 若想實現其它功能請自行完善

5、運行結果:(大體會出現如下界面)

 

 

 

6、定時自動執行腳本

  1. 注意安裝並啓動crontabs服務。參考:http://www.javashuo.com/article/p-fusxhefu-hw.html
  2. 執行命令安裝並啓動:
    • yum -y install crontabs
    • systemctl start crond
  3. (即天天的十點十分定時對cpu、內存、磁盤進行監控)

     

 

2018-10-2015:35:24

相關文章
相關標籤/搜索