tomcat监控脚本(监控进程,测试接口,告警动作为发送邮件)

服务器环境:centos7.2 64位 tomcat8.5.6

tomcat 监控功能共需要两个脚本,如下:
initMonitor.sh

#!/bin/sh
#初始化监控脚本相关变量
export tomcat_name=apache-tomcat-8.5.6
export tomcat_home=/usr/local/apache-tomcat-8.5.6
#测试接口访问地址
export webUrl=127.0.0.1:8080/yanglao/sysUserController/sysTest
#监控脚本日志路径
export tomcatMonitorLog=/tmp/yanglao/tomcatMonitor.log
export [email protected]
#执行tomcat监控脚本

#获取当前脚本所在目录
baseDirForScriptSelf=$(cd "$(dirname "$0")"; pwd)
$baseDirForScriptSelf/tomcatMonitor.sh

tomcatMonitor.sh

#!/bin/sh
# 获取tomcat进程ID  /usr/local/tomcat_ds_api
TomcatID=$(ps -ef |grep tomcat |grep -w $tomcat_name|grep -v 'grep'|awk '{print $2}')  
# tomcat启动程序
StartTomcat=$tomcat_home/bin/startup.sh
# 日志输出 
if [ -f $tomcatMonitorLog ]; then
   echo "日志文件已创建"
else
   echo "日志文件为创建,马上创建!"
    touch $tomcatMonitorLog
fi
#tomcatMonitorLog=/tmp/yanglao/tomcatMonitor.log 
TryConnection(){
    echo $tomcat_name 
    echo '$tomcat_name'
  TryTomcatID=$(ps -ef |grep tomcat |grep -w $tomcat_name|grep -v 'grep'|awk '{print $2}')  
  echo "[info]开始重新查看tomcat进程:$TryTomcatID...[$(date +'%F %H:%M:%S')]"  
  if [[ $TryTomcatID ]];then
    echo "[info]当前tomcat进程ID为:$TryTomcatID,继续重新检测接口..."  
    # 检测是否启动成功(成功的话接口会返回状态"200")  
    TomcatServiceCodeTry=$(curl -s -m 10 --connect-timeout 10 $webUrl -w %{http_code}) 
    if [[ $TomcatServiceCodeTry -eq 200 ]];then  
        echo "[info]系统接口返回码为$TomcatServiceCodeTry,tomcat重启成功,访问系统接口正常......"  
        echo "[error]发送告警关闭邮件"  
        echo "tomcat重启成功,访问系统接口正常 [$(date +'%F %H:%M:%S')]"|mail -s "智能养老项目告警关闭" $email_address
    else
    sleep 30
    TryConnection
    fi  
  else 
    sleep 30
    TryConnection
  fi
}

Monitor() 
{  
  echo "[info]开始监控tomcat...[$(date +'%F %H:%M:%S')]"  
  if [[ $TomcatID ]];then # 这里判断TOMCAT进程是否存在  
    echo "[info]当前tomcat进程ID为:$TomcatID,继续检测系统接口..."  
    # 检测是否启动成功(成功的话接口会返回状态"200")  
    TomcatServiceCode=$(curl -s -m 10 --connect-timeout 10 $webUrl -w %{http_code}) 
    if [[ $TomcatServiceCode -eq 200 ]];then
        echo "[info]接口返回码为$TomcatServiceCode,tomcat运行正常,访问系统接口正常......"  
    else  
        echo "[error]访问系统接口出错,请注意......状态码为$TomcatServiceCode"  
        echo "[error]访问系统接口出错,开始重启tomcat"  
        echo "[error]发送告警开启邮件"  
        echo "由于访问系统接口出错,tomcat开始自动重启 [$(date +'%F %H:%M:%S')]"|mail -s "智能养老项目告警开启" $email_address
        kill -9 $TomcatID  # 杀掉原tomcat进程  
        sleep 3  
        rm -rf $TomcatCache # 清理tomcat缓存  
        $StartTomcat  
        sleep 3m
        TryConnection #检查是否启动成功
    fi  
  else  
    echo "[error]tomcat进程不存在!tomcat开始自动重启..."  
    echo "[info]$StartTomcat,请稍候......"  
    echo "[error]发送告警开启邮件"  
    echo "由于tomcat进程不存在   tomcat开始自动重启 [$(date +'%F %H:%M:%S')]"|mail -s "智能养老项目告警开启" $email_address
    rm -rf $TomcatCache  
    $StartTomcat  
    sleep 3m
    TryConnection #检查是否启动成功
  fi  
  echo "------------------------------"  
}  
Monitor>>$tomcatMonitorLog

前期准备:

  1. 安装crontab
  2. 配置邮件发送环境

脚本介绍:

  1. initMonitor.sh中可配置脚本中使用的变量,除参数配置外,此脚本中将调用tomcatMonitor.sh,此脚本再次调用的原因是export所设置的变量,仅在该shell以及它的子shell中有效。
  2. tomcatMonitor.sh为tomcat监控的业务逻辑脚本

使用说明:
1.将initMonitor.sh,tomcatMonitor.sh两个脚本放入服务器同级目录下(如:/usr/bin/yanglao)
2.如需配置脚本对应变量,请编辑initMonitor.sh,不需要更改的可跳过此步
3.使用crontab设置定时执行initMonitor.sh:
1)# crontab -e
2 )插入/5 * * * /usr/bin/yanglao/initMonitor.sh
3)#systemctl reload crond
#systemctl restart crond
经过以上操作,脚本即可运行,开始检测tomcat。

检测范围:tomcat进程关闭 , 系统接口无法访问
告警动作:发送邮件至initMonitor.sh设置的邮件,并重启tomcat。
重启后对tomcat重新进行检测,检测运行正常后,发送告警关闭邮件


分界线———–更于2017.08.07


由于最近开发的产品总是莫名其妙挂掉(我怀疑是我关了忘启动。。。),决定为该产品添加监控脚本。由于产品是直接面对普通用户的,为防止脚本因为莫名其妙的问题反复重启项目,故将项目启动部分去掉,改为只负责监控,不对项目执行任何操作。
另外本次遇到的另一个蛋疼的问题是阿里云不允许通过smtp协议直接走25端口发送邮件,我又是个Linux菜鸡,实在没找到linux通过smtp协议发送邮件的方法,只能绕个路,通过java打jar包去发送smtps协议的邮件了。。。。送上代码:

initMonitor-wechat.sh

#!/bin/sh
#初始化监控脚本相关变量
export tomcat_name=/data/apache-tomcat-7.0.75
export tomcat_home=/data/apache-tomcat-7.0.75
#测试接口访问地址
#export webUrl=http://www.test.com/test
#监控脚本日志路径
export tomcatMonitorLog=/data/tomcatMonitor/log/tomcatMonitor-wechat.log
#export [email protected]
#执行tomcat监控脚本

#获取当前脚本所在目录
baseDirForScriptSelf=$(cd "$(dirname "$0")"; pwd)
echo $baseDirForScriptSelf
$baseDirForScriptSelf/tomcatMonitor-wechat.sh

tomcatMonitor-wechat.sh

#!/bin/sh
# 日志输出 
TomcatID=$(ps -ef |grep tomcat |grep -w $tomcat_name|grep -v 'grep'|awk '{print $2}')
if [ -f $tomcatMonitorLog ]; then
   echo "日志文件已创建"
else
   echo "日志文件为创建,马上创建!"
    touch $tomcatMonitorLog
fi


Monitor() 
{
  echo "[info]开始监控$tomcat_home...[$(date +'%F %H:%M:%S')]"  
  if [[ $TomcatID ]];then # 这里判断TOMCAT进程是否存在  
    echo "[info]当前$tomcat_home进程ID为:$TomcatID,继续检测系统接口..."  
    # 检测是否启动成功(成功的话接口会返回状态"200")  
    TomcatServiceCode=$(curl -s -m 10 --connect-timeout 10 http://wx.test.com/bxg/user/login -o /dev/null -w %{http_code})
    if [[ $TomcatServiceCode -eq 200 ]];then
        echo "[info]接口返回码为$TomcatServiceCode,$tomcat_home.运行正常,访问系统接口正常......"  
    else
        echo "[error]访问系统接口出错,请注意......状态码为$TomcatServiceCode"  

        echo "[error]发送告警开启邮件"  
        echo "访问系统接口出错[$(date +'%F %H:%M:%S')]"
        /data/jre/bin/java -jar /data/tomcatMonitor/lib/wechat.jar
        echo "访问系统接口出错[$(date +'%F %H:%M:%S')]"
    fi
   else
    echo "[error]$tomcat_home进程不存在!"  
    echo "[error]发送告警开启邮件"  
    echo "$tomcat_home进程不存在 [$(date +'%F %H:%M:%S')]"
    /data/jre/bin/java -jar /data/tomcatMonitor/lib/wechat.jar
    echo "$tomcat_home进程不存在 [$(date +'%F %H:%M:%S')]"
  fi
  echo "------------------------------" 
}
Monitor>>$tomcatMonitorLog

使用java通过smtps协议发送Email的代码

wechat.jar


import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {
     public static boolean sendMailBySSL(String email) throws AddressException, MessagingException{
          Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
          final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
          // Get a Properties object
          Properties props = new Properties();
          props.setProperty("mail.smtp.host", "smtp.test.com");
          props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
          props.setProperty("mail.smtp.socketFactory.fallback", "false");
          props.setProperty("mail.smtp.port", "465");
          props.setProperty("mail.smtp.socketFactory.port", "465");
          props.put("mail.smtp.auth", "true");
          final String username = "[email protected]";
          final String password = "test";
          Session session = Session.getDefaultInstance(props, new Authenticator(){
              protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(username, password);
              }});

               // -- Create a new message --
          Message msg = new MimeMessage(session);

          // -- Set the FROM and TO fields --
          msg.setFrom(new InternetAddress("[email protected]"));
          msg.setRecipients(Message.RecipientType.TO, 
            InternetAddress.parse(email,false));
          msg.setSubject("后台管理告警开启");
          SimpleDateFormat formatter;
          formatter = new SimpleDateFormat ("yyyy.MM.dd G 'at' hh:mm:ss z"); 
          msg.setText("后台管理告警开启 ["+formatter.format(new Date())+"],请及时处理");
          msg.setSentDate(new Date());
          Transport.send(msg);

          System.out.println("Message sent.");
          return true;
         }

   public static void main(String[] args) throws AddressException, MessagingException {
        sendMailBySSL("[email protected]");
    }
}

该代码块引用了mail-1.4.jar

你可能感兴趣的:(linux)