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

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

老套路,先梳理思路mysql

監控apache web服務

監控mysql數據庫

監控服務器硬盤使用狀況

監控服務器的內存使用

  廢話很少說,直接上代碼linux

1.apache web 服務器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.監控mysqlsql

!/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 apache

#!/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

 整合一下bash

#!/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,編寫計劃,自動監控,天天發送一份報告,這樣天天我都會收到服務器的一個狀態less

 

crontab -e

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

相關文章
相關標籤/搜索