###
""" 判断一个进程是否存活,如果进程挂掉就会重启某个进程,并且发送邮件通知。邮件使用HTML """ from __future__ import print_function from collections import OrderedDict import os, sys, time import smtplib from email.mime.text import MIMEText from email.header import Header #负载信息 def load_stat(): loadavg = {} f = open("/proc/loadavg") con = f.read().split() f.close() loadavg['lavg_1'] = con[0] loadavg['lavg_5'] = con[1] loadavg['lavg_15'] = con[2] loadavg['nr'] = con[3] loadavg['last_pid'] = con[4] return loadavg #内存信息 def meminfo(): ''' Return the information in /proc/meminfo as a dictionary ''' meminfo = OrderedDict() with open('/proc/meminfo') as f: for line in f: meminfo[line.split(':')[0]] = line.split(':')[1].strip() return meminfo # meminfo = meminfo() # print('Total memory: {0}'.format(meminfo['MemTotal'])) # print('Free memory: {0}'.format(meminfo['MemFree'])) def nojsmail(x, y): # 第三方 SMTP 服务 mail_host = "smtp.exmail.qq.com" # 设置服务器这个是qq mail_user = "linwen@xxxxx.com" # 用户名 mail_pass = "xxxxx" # 口令 sender = 'linwen@xxxxx.com' receivers = ['linwen@xxxxx.com'] # mail_msg=str(timestamp) + ':' + 'Nodejs断开重启了 ' + str(sys.exc_info()[1]) mail_msg = """ <p>NodeJS 进程异常退出,4 秒后重新启动...</p> <p>--------------------------------------</p> """ + 'Total memory: ' + str(meminfo['MemTotal']) + '<br > ' + 'Free memory: ' + str( meminfo['MemFree']) + '<br >' + "loadavg :" + str(load_stat()['lavg_15']) message = MIMEText(mail_msg, 'html', 'utf-8') message['From'] = Header("linwensheng", 'utf-8') message['To'] = Header("linwensheng", 'utf-8') subject = 'Python 监控NodeJs邮件测试' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号 smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print("邮件发送成功") except smtplib.SMTPException: print("Error: 无法发送邮件") if __name__ == "__main__": ret = os.popen('ps -C mysqld -o pid,cmd').readlines() if len(ret) < 3: print('NodeJS 进程异常退出,4 秒后重新启动') time.sleep(3) os.system("service mysqld restart >/dev/null 2>&1") timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) meminfo = meminfo() nojsmail(meminfo, load_stat)
###