shell實現腳本監控服務器及web應用


   實際工作中我們需要知道部署在服務器上的應用有沒有問題,但是人為的操作太麻煩有咩有簡單的方式呢shell來監控我們服務器運行狀態以及服務器上部署的應用,如果出現異常就會自動發送一個郵件給我們,開始搞起。。。

老套路,先梳理思路

監控apache web服務

監控mysql數據庫

監控服務器硬盤使用情況

監控服務器的內存使用

  廢話不多說,直接上代碼

1.apache web 服務器

!/bin/bash
# 表示請求鏈接3秒鍾,不要返回的測試數據
nc -w 3 localhost 80 &>/dev/null
if [ $? -eq 0 ];then
        str="apache web status Running!"
else
        str="apache web status Shuting!"
fi
# 發送的主題,郵件地址
echo str|mail -s 'apache web server' admin@lampym.com

2.監控mysql

!/bin/bash
# 表示請求鏈接3秒鍾,不要返回的測試數據
nc -w 3 localhost 3306 &>/dev/null
if [ $? -eq 0 ];then
        str="mysql server status Running!"
else
        str="mysql server status Shuting!"
fi
# 發送的主題,郵件地址
echo str|mail -s 'mysql server status' admin@lampym.com

3.監控服務器disk

#!/bin/bash
:<<!
NR表示行數,$5表示第5列,具體的自己根據實際調整
!
ds=`df |awk '{if(NR==4){print int($5)}}'`
# 這里45根據實際需要更改
if [ $ds -lt 45 ];then
	str="disk space is less then!!!"
else
	str="disk space is greate than 45%!!!"
fi
echo $str|mailx -s 'linux server disk space' admin@lampym.com

4.監控服務器monery 

#!/bin/bash
:<<!
具體的自己根據實際調整
!
mery=`df |awk '{if(NR==2){print int($3*100/$2)}}'`
if [ $mery -lt 50 ];then
	str="mery space is less then 50%!!!"
else
	str="mery space is greate than 50%!!!"
fi
echo $str|mailx -s 'linux server mery space' admin@lampym.com

 整合一下

#!/bin/bash
# 功能:監控資源
# 名稱:cont.sh
# 作者:楓客浪人
# 版本:0.1
# 聯系方式:xxxx
# apache 應用服務 
apache_web(){
    nc -w 3 localhost 80 &>/dev/null
  if [ $? -eq 0 ];then
        str="apache web status Running!"
  else
        str="apache web status Shuting!"
  fi
    # 發送的主題,郵件地址
  echo str|mail -s 'apache web server' admin@lampym.com
}
# mysql 服務
mysql_db(){
    nc -w 3 localhost 3306 &>/dev/null
    if [ $? -eq 0 ];then
        str="mysql server status Running!"
    else
        str="mysql server status Shuting!"
    fi
        # 發送的主題,郵件地址
    echo str|mail -s 'mysql server status' admin@lampym.com 
}
# 磁盤使用情況
disk_mnt(){
    ds=`df |awk '{if(NR==4){print int($5)}}'`
    # 這里45根據實際需要更改
    if [ $ds -lt 45 ];then
        str="disk space is less then!!!"
    else
	str="disk space is greate than 45%!!!"
    fi
    echo $str|mailx -s 'linux server disk space' admin@lampym.com
}
# 內存使用情況
meny_mnt(){
    mery=`df |awk '{if(NR==2){print int($3*100/$2)}}'`
    if [ $mery -lt 50 ];then
	str="mery space is less then 50%!!!"
    else
	str="mery space is greate than 50%!!!"
    fi
    echo $str|mailx -s 'linux server mery space' admin@lampym.com
}
min(){
apache_web()
mysql_db()
disk_mnt()
meny_mnt()
}

 

  個人覺得還可將腳本更加復雜化,加入更多我們想要的信息,比如報錯后具體的錯誤信息等等,當然這只是簡單的例子,如果有需要,小伙伴們可以自己添加自己需要的內容。。。。。

 

  關於自動監控策略,我這里采用的是Linux中的定時crontab,編寫計划,自動監控,每天發送一份報告,這樣每天我都會收到服務器的一個狀態

 

crontab -e

每天13:10分執行代碼發送一份郵件

 

 

  


免責聲明!

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



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