Python实现对Tomcat的监控

Python实现对Tomcat的监控


  
最近发现tomcat经常会僵死。而PS查看进程的时候进程还在。但不提供服务了。程序的功能:定期对tomcat服务器发送指命,如果得到响应,则服务器正常,否则异常,同时发邮件给相关人员。

#! /usr/bin/env python
# -*- coding: gb2312 -*-
import socket,time
import re #正则包
import ElementTree as ET
import ConfigParser
import base64,time,smtplib
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart

#import xml.etree.ElementTree as ET
def WriteLog(filename,tmpstr):
 
    time_str =time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
      logstr =str(tmpstr) + '\n'
      f =open(filename,"a")
      f.write(logstr)
      f.close()
def ReWriteLog(filename,tmpstr): #用写模式找开文件
      time_str =time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
      logstr =str(tmpstr) + '\n'
      f =open(filename,"w")
      f.write(logstr)
      f.close()
def getMailConfig(configFile):
      coms=[]
      Config =ConfigParser.ConfigParser()
      Config.read(configFile)
      host =Config.get("FROM","HOST")
      user =Config.get("FROM","USERNAME")
      subject =Config.get("FROM","SUBJECT")
      pwd =base64.b64decode(Config.get("FROM","PASSWORD"))
      commands =Config.items("TO")
      for com incommands:
              coms.append(com[1])
      returnhost,user,pwd,subject,coms
def SendMail(configFile,sendfile,logFile):
      host,user,pwd,subject,coms=getMailConfig(configFile)
      _tos=""
      for _to incoms:
              _tos = _tos + _to + ";"
      msg =MIMEMultipart()
            # att = MIMEText("test mail")
      att =MIMEText(open(sendfile,'rb').read(),'base64','gb2312')
    att["Content-Type"] ='application/octet-stream'
      att["Content-Disposition"]='attachment;filename="'+sendfile+'"'
          msg.attach(att)
          msg['to']=coms
      msg['from']=user
      msg['to']=_tos
      msg['subject']=subject+" "+time.strftime("%Y-%m-%d",time.localtime())
      msg.attach(att)
      try:
              smtp_svr=smtplib.SMTP()
              smtp_svr.connect(host,"25")
      except(smtplib.SMTPConnectError,socket.error):
              print "connect error"
              WriteLog(logFile,"connect error")
      try:
              smtp_svr.login(user,pwd)
      exceptsmtplib.SMTPAuthenticationError:
              print "authentication error\n"
              WriteLog(logFile,"authentication error")
      try:
              smtp_svr.sendmail(user,coms,msg.as_string())
      except(smtplib.SMTPRecipientsRefused,smtplib.SMTPDataError,smtplib.SMTPServerDisconnected):
              print "send mail error"
              WriteLog(logFile,"send mail error")
      smtp_svr.close
             
defSendMailForHtml(configFile,tableContent,mailtitle,logFile):
      host,user,pwd,subject,coms=getMailConfig(configFile)
      _tos=""
      for _to incoms:
              _tos = _tos + _to + ";"
      #
    smtp_server= smtplib.SMTP(smtp_host)  
      msg =MIMEMultipart()
      html='<html><body>'+tableContent+'</body></html>' 
      msg =MIMEText(html, 'html')  
      msg['from']=user
      msg['to']=_tos
      msg['subject']=subject + " " + mailtitle
      try:
              smtp_svr=smtplib.SMTP()
              smtp_svr.connect(host,"25")
      except(smtplib.SMTPConnectError,socket.error):
              print "connect error"
              WriteLog(logFile,"connect error")
      try:
              smtp_svr.login(user,pwd)
      exceptsmtplib.SMTPAuthenticationError:
              print "authentication error\n"
              WriteLog(logFile,"authentication error")
      try:
              smtp_svr.sendmail(user,coms,msg.as_string())
      except(smtplib.SMTPRecipientsRefused,smtplib.SMTPDataError,smtplib.SMTPServerDisconnected):
              print "send mail error"
              WriteLog(logFile,"send mail error")
      smtp_svr.close

def main():
      maillogFile= 'checkTomcatMail.log'
      prologFile ='checkTomcat.log'
      mailConf ='ini/Mail.ini'
      proConf ='ini/checkTomcat.xml'
    proConf ='checkTomcat.xml'
     
      flag =True
      mailTitle =''
      mailContent='<table><tr><td>serviceName</td>IP<td>Prot</td><td>Type</td><td>result</td></tr>'
     
      root =ET.parse(proConf).getroot()
      allservice =root.findall('ServiceInfo')
      for serverin allservice:
              sIP = server.find('IP').text
              sName = server.find('Name').text
              sType = server.find('Type').text
              sPort = server.find('Port').text
              try:
                      clisock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                      clisock.connect((sIP,int(sPort)))
                      clisock.send("GET TomcatHTTP/1.1\r\nHost:192.168.22.15\r\n\r\n")
                      clisock.settimeout(5)
                      hostlocal = clisock.recv(100)
                      p = re.compile('HTTP/1.1')
                      abc1 =p.findall(hostlocal)
                      if len(abc1)==1:
                              mailContent = mailContent +'<tr><td>'+sName+'</td><td>'+sIP+'</td><td>'+sPort+'</td><td>'+sType+'</td><td>OK</td></tr>'
                      else:
                              mailContent = mailContent +'<tr><td>'+sName+'</td><td>'+sIP+'</td><td>'+sPort+'</td><td>'+sType+'</td><td><fontcolor=red>WARNING</font></td></tr>'
                              mailTitle = mailTitle + sName + '(' + sIP + ') is WARNING'
                              flag = False
                      clisock.close()
              except:
                      mailContent = mailContent +'<tr><td>'+sName+'</td><td>'+sIP+'</td><td>'+sPort+'</td><td>'+sType+'</td><td><fontcolor=red>Error</font></td></tr>'
                      mailTitle = mailTitle + sName + '(' + sIP + ') is TimeOutError'
                      flag = False
     
    printmailContent
      WriteLog(prologFile,mailContent)
      time_str =time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
      if notflag:
              SendMailForHtml(mailConf,mailContent,mailTitle,maillogFile)
              WriteLog(maillogFile,time_str+ mailTitle + " send mail OK")
                     
     
if __name__=='__main__':
      main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值