热度: |
项目中某个组件经常性出问题,重启下便好了。所以写个脚本每天跑一下重启组件。并且监控组件状态,如果启动失败,自动发送通知邮件到指定邮箱。
1. 在Linux系统上使用crontab 命令定时(循环)执行某个任务的程序
crontab -l //列出某个用户cron服务的详细内容
crontab filename //根据文本内容设定定时作业
这里我新建一个cron.txt , 内容为 01 2 * * * /home/oracle/cron/comp_sfs.sh
然后执行 crontab cron.txt,任务会被自动加载,因为Cron服务会每隔一分钟Check所有的任务。
2. 编写重启脚本 comp_sfs.sh
Siebel 提供了服务器组件、任务、会话管理命令行接口,(Siebel Component Manage Command Line Interface),并提供了 /b 等批处理参数,执行批处理时可以将输入的命令全部保存到文件,从文件加载命令,如果要使用awk获取命令执行后返回的组件状态,则必须定制返回结果的显示列,使用 configure list comp show column1,column2,column3,……,这里我只定制输出了当前运行的用户数,运行状态,组件别名等不包含空格的列(awk输出是用空格做分隔符)。捕获状态后根据状态值确定组件是否正常,正常启动的状态应该为 Online 或 “在线”,如是其他状态则发送通知邮件。
#!/bin/sh
logfile=/home/oracle/cron/component.logcommand=$1cp=$2tempfile=command.txtdefaultcomp=SFSObjMgr_chsdefaultcmd=restartsrvrcmd="srvrmgr /g crmtst /s crmtst /e TEST /u SADMIN2 /p SADMIN2 "
envpath=". /oracle/app/siebel/siebsrvr/siebenv.sh"
configlist="configure list comp show CC_ALIAS,CP_DISP_RUN_STATE,CP_NUM_RUN_TASKS,CP_MAX_TASKS,CP_ACTV_MTS_PROCS,CP_MAX_MTS_PROCS "
notifyprogram="python /home/oracle/cron/YEmail.py"
if [ "${command}" == "" ]then
command=${defaultcmd}fiif [ "${cp}" == "" ]then
cp=${defaultcomp}fi${envpath}echo -e ${configlist} > $tempfileecho list comp ${cp} >> $tempfilepreusers=`${srvrcmd} /b /i $tempfile | grep $cp | grep -v "srvrmgr" | awk '{ print $3 }'`echo -e "#---------------------- Component Operate ------------------------#" >> ${logfile}
if [ "${command}" == "restart" ]then
echo Load Component: ${cp} >> ${logfile}echo Operate Action: ${command} >> ${logfile}echo Kill Component ${cp} ... >> ${logfile}${srvrcmd} /b /c "kill comp ${cp}" | grep ${cp} | grep -v "srvrmgr"sleep 2
echo Start Component ${cp} ... >> ${logfile}${srvrcmd} /b /c "startup comp ${cp}" | grep ${cp} | grep -v "srvrmgr"else
echo ${command} Component ${cp} ... >> ${logfile}${srvrcmd} /b /c "${command} comp ${cp}" | grep ${cp} | grep -v "srvrmgr"sleep 1
fires=`${srvrcmd} /b /i $tempfile | grep $cp | grep -v "srvrmgr" `
status=`echo $res | awk '{ print $2 }'`
echo Check Componnet Status: ${status} >> ${logfile}if [ "${status}" != "Online" -a "${status}" != "运行中" ]then
${notifyprogram}echo Server Component Not Runing Normal ,Email Sentfiecho Check Componnet Status: ${status} >> ${logfile}echo Before Operate Running User Number: ${preusers} >> ${logfile}echo Operate DateTime: $(date +"%Y/%m/%d %T") >> ${logfile}
echo -e "#--------------------------- End -------------------------------#\n" >> ${logfile}
rm $tempfile3. 邮件通知程序
linux本身是支持发送邮件的,有相关命令,但前面我写过一个python 发送邮件的脚本,就用现成的了。
# -*- coding: gbk -*-'''Created on 2011-1-27@author: Spring'''import email
import mimetypes
import random
import timefrom datetime import datetime
import stringfrom email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib
class YEmail(object):
'''classdocs'''def __init__(self, configProfile):
self.authInfo = configProfile.get("EMAIL")
if not self.authInfo:
raise "请为配置文件添加SSH模块,参数见文档"
self.fromAdd = self.authInfo["admin_email"]
self.subject = self.authInfo["admin_subject"]
self.mailContentFile = self.authInfo["content_file"]
self.email_file = self.authInfo["addrs_file"]
self.isLog = bool(self.authInfo.get("enable_log"))
self.log_file_path = self.authInfo["log_file_path"]
self.isHtml = self.authInfo["content_type"]
self.default_admin=self.authInfo.get("admin_name")
self.currentMsg = ""def enableLog(self):
'''Enable Log,Create Log File'''self.isLog = Trueself.log_file = open(self.log_file_path, 'a')
def logger(self, msg):
'''Log Recorder'''if self.isLog:
if not self.log_file:
self.log_file = open(self.log_file_path, 'a')
self.log_file.write(datetime.now().strftime("%Y/%m/%d %H:%M:%S%p") + " ## "+msg + "\n\n")
self.currentMsg = msgprint msg + "\n\n"def sendEmail(self, fromAdd, toAdd, subject, content, isHtml):
'''Send Mail, param is Sender,Receivers,Subject , Content, is or not HTML'''strFrom = fromAddstrTo = toAdd.replace(",", ";")listTo = strTo.split(";")server = self.authInfo.get('smtp_server')user = self.authInfo.get('user')passwd = self.authInfo.get('password')if not (server and user and passwd) :self.logger('邮件配置信息错误,登陆邮件服务器失败~!')return False
# 设定root信息msgRoot = MIMEMultipart('related')msgRoot['Subject'] = subjectmsgRoot['From'] = strFrommsgRoot['To'] = ', '.join(listTo)
# Encapsulate the plain and HTML versions of the message body in an# 'alternative' part, so message agents can decide which they want to display.msgAlternative = MIMEMultipart('alternative')msgRoot.attach(msgAlternative)#设定纯文本信息if isHtml == False :
msgText = MIMEText(content, 'plain', 'gbk')msgAlternative.attach(msgText)else:
#设定HTML信息msgText = MIMEText(content, 'html', 'gbk')msgAlternative.attach(msgText)#设定内置图片信息#fp = open('1.jpg', 'rb')
#msgImage = MIMEImage(fp.read())
#fp.close()
#msgImage.add_header('Content-ID', '<image1>')#msgRoot.attach(msgImage)#发送邮件smtp = smtplib.SMTP()#设定调试级别,依情况而定smtp.set_debuglevel(1)smtp.connect(server)smtp.login(user, passwd)
smtp.sendmail(strFrom, listTo, msgRoot.as_string())return True
def getBody(self):
'''Get Email Body from file,Can be html ,or plain text'''f_body = open(self.mailContentFile, 'r')
plainText = f_body.read()
f_body.close()
return plainText
def getContacts(self):
'''Get Contacts's Info ,and email address, split by ',' ,First is User ID or
Name,others is eamil address'''contacts = []try:f_contacts = open(self.email_file, "r")commentLine = 0for line in f_contacts:if line[0] == "#":commentLine = commentLine + 1continueif line[-1] != '\n':
line = line + "\n"
try:contact = {}contact["name"] = line.split(',')[0]contact["email"] = line[line.index(',') + 1:-1]self.logger("联系人: " + contact["name"] + ", 地址 " +contact["email"])
contacts.append(contact)except :self.logger("行: " + line + " ------- 出现异常")continuef_contacts.close()
self.logger("注释行 :" + str(commentLine))
self.logger("有效行 :" + str(len(contacts)))
self.logger("/*------------------- 联系人地址识别结束 --------------------*/")
except Exception:contacts.append({"name":self.default_admin,
"email":self.fromAdd
})return contacts
def multiSend(self,dictargs={}):
'''More than one contact email address,but every people will receive single .dict args are "arg":"value" dictionary ,instead of @[arg] to value in contentfile'''self.enableLog()self.logger("/*==================== 根据联系人列表发送邮件
=====================*/")
try:#邮件内容htmlText = self.getBody()#收信人邮件地址列表contacts = self.getContacts()except Exception:raise "联系人列表和邮件内容模板路径错误!"
#记录发送进度self.logger("/*------------------- 开始发送邮件 --------------------*/")
i = 0j = 0for line in contacts:try:addr = str(line["email"])
contact = str(line["name"])
htmlText = htmlText.replace("[@Name]",contact)for args in dictargs.keys():htmlText = htmlText.replace("[@%s]" % args, dictargs[args])self.sendEmail(self.fromAdd, addr, self.subject, htmlText, self.isHtml)self.logger(str(i + 1) + "\t" + contact + "\t" + addr + ' ------------ ' +'OK.')i = i + 1except Exception:j = j + 1self.logger(str(i + 1) + "\t" + contact + "\t" + addr + ' ------------ ' +'Error.')raisecontinueself.logger("成功发送 " + str(i) + " 个联系人,失败 " + str(j) + " .")self.closeLog()def closeLog(self):
'''close log
'''if self.log_file and not self.log_file.closed:
self.log_file.close()
if __name__ == "__main__":#用于测试configProfile = {"email":{
"smtp_server":"10.192.224.16","user":'out-luchunlong@cn.panasonic.com' ,
"password":'ysisl11#' ,
"content_file":"body.txt","addrs_file" : 'addrs.txt',
"enable_log":False,
"log_file_path":"email_log.txt","content_type":"html","admin_email":"Manager <out-luchunlong@cn.panasonic.com>","admin_subject":"系统维护监控程序异常通知邮件"}}#Config 引擎测试from YConfig import YConfig
cfg = YConfig()configProfile = cfg.cfgdictm = YEmail(configProfile)dictargs = {"Content" : "组件启动失败","date" : datetime.now().strftime("%Y-%m-%d %H:%M:%S%p")}m.multiSend(dictargs)