实际业务中需要监控tomcat服务器是否异常关闭
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import time
import socket
import smtplib
from email.mime.text import MIMEText
# 第三方 SMTP 服务
mail_host="smtp.qq.com" #设置服务器
# 发送方信息
mail_user="XXX@qq.com" #用户名
mail_pass="xxxxxx" #口令
# 收件人列表
mail_namelist = ["xxxxxx@qq.com", "xxxxxxx@qq.com"]
def restartTomcat():
time.sleep(5)
os.system("sh /data/tomcat/bin/shutdown.sh")
time.sleep(30)
os.system("sh /data/tomcat/bin/startup.sh")
#发送邮件
#title:标题
#conen:内容
def send_qq_email(title,conen,format='plain'):
try:
msg = MIMEText(str(conen),format,'utf-8')
#设置标题
msg["Subject"] = title
# 发件邮箱
msg["From"] = mail_user
#收件邮箱
msg["To"] = ";".join(mail_namelist)
# 设置服务器、端口
s = smtplib.SMTP_SSL(mail_host, 465)
#登录邮箱
s.login(mail_user, mail_pass)
# 发送邮件
s.sendmail(mail_user, mail_namelist, msg.as_string())
s.quit()
print("邮件发送成功!")
restartTomcat()
return True
except smtplib.SMTPException:
print("邮件发送失败!")
return False
def checkMonitor():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1', 56823))
if result == 0:
print("进程存在")
else:
send_qq_email("监控系统服务异常", "检测不到监控系统进程")
checkMonitor()
每5分钟执行一次
*/5 * * * * python /data/monitorSendMail.py
添加完需要重启crontab使之立即生效
/etc/init.d/cron restart