使用python来检查进程是否存在,如果不存在就邮件提醒,并且每日发送一份整体报告
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' Description: check progress is existed? Named: check_progress.py Author: Icyboy Email: xupeng.js@gmail.com Execute: */30 * * * * python check_progress.py >/dev/null 2>&1 ''' import os, time import smtplib from email.mime.text import MIMEText host = '360' check_progress = ['cpcdaemon.php', 'nginx', 'mysql', 'redis', 'supervisor', 'tomcat', 'php-fpm', 'mongodb', 'memcached'] day_send_mail_time = '10:00' mailto_list = ["xupeng@jiunile.com", "xxx@jiunile.com"] mail_host = "smtp.163.com" mail_user = "xxx@163.com" mail_pass = "xxx" mail_postfix = "163.com" def send_mail(sub, content): me = mail_user + "<" + mail_user + "@" + mail_postfix + ">" msg = MIMEText(content) msg['Subject'] = sub msg['From'] = me msg['To'] = ";".join(mailto_list) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user, mail_pass) s.sendmail(me, mailto_list, msg.as_string()) s.close() return True except Exception, e: log("Unexpected error:" + str(e)) return False def progress_exist(progress_name): try: progress_num = int(os.popen('ps -ef | grep ' + progress_name + ' | grep -v grep | wc -l').read()) if progress_num > 0: return {'name': progress_name, 'status': 1} else: return {'name': progress_name, 'status': 0} except Exception, e: log("Unexpected error:" + str(e)) return {'name': progress_name, 'status': 0} def log(msg): dateNow = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) logStr = '%s : %s \n' % (dateNow, msg) logfile.write(logStr) if __name__ == '__main__': logfile = open("/tmp/tmp.log", "a") nowTime = time.strftime('%H:%M', time.localtime()) lists = [] for progress_name in check_progress: status = progress_exist(progress_name) lists.append(status) bad_msg = 'not run progress:' good_msg = 'progress is run ok! ' flag = 1 for list in lists: if list['status'] == 0: bad_msg += list['name'] + ' ' flag = 0 else: good_msg = list['name'] + ' ' + good_msg if flag == 0: log(bad_msg) send_mail(host + ' progress check bad', bad_msg) else: bad_msg = '' log(good_msg) if nowTime == day_send_mail_time: #发送整体邮件 df = os.popen('df -h').read() send_mail(host + ' progress status', good_msg + bad_msg + "\n\n" + df) logfile.close()