def sendmail(maildata): sender = tools.readconfig('mail', 'sender') receiver = tools.readconfig('mail', 'receiver') subject = tools.readconfig('mail', 'subject') smtpserver = tools.readconfig('mail', 'smtpserver') username = tools.readconfig('mail', 'username') password = tools.readconfig('mail', 'password') attachfile = tools.readconfig('mail', 'attachfile') msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) msgText = MIMEText(date + maildata, _subtype='plain', _charset='gb2312') msgRoot.attach(msgText) # 构造附件 if attachfile != '': att = MIMEText(open(attachfile, 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="parameter.ini"' msgRoot.attach(att) smtp = smtplib.SMTP() smtp.connect(smtpserver) # smtp.login(username, password) smtp.sendmail(sender, receiver, msgRoot.as_string()) smtp.quit() tools.writeLog('邮件已发送给:' + receiver)
def verifycommond(fromuserid , usercommond): ''' 校验发送命令的用户ID和命令,根据命令执行相对于的job 返回:查询结果 string类型 ''' global MONITOR_RESULT global LASTDONETIME # 检查命令间隔时间,如果过于频繁,将不执行命令 tools.writeLog('收到来自用户' + fromuserid + '的命令:' + usercommond) if usercommond == SPECIAL_CMD and '[' + fromuserid + ']' in SPECIAL_USERID: #执行实时查询命令 MONITOR_RESULT = domyjob() return MONITOR_RESULT elif usercommond == MONITOR_CMD : #如果从未执行过,则执行一次,并一直返回该结果 #控制普通用户命令最低间隔时间 if MONITOR_RESULT == None or '系统运行状态'not in MONITOR_RESULT \ or datetime.datetime.now() >= LASTDONETIME + datetime.timedelta(seconds=MONITOR_INTERVALTIME): MONITOR_RESULT = domyjob() return MONITOR_RESULT elif usercommond == '?': return '输入以下命令查询结果:监控结果' else: return '八哥学语:' + usercommond
def onAction(self, action): tools.writeLog('Action received: ID %s' % str(action.getId())) if (action == ACTION_NAV_BACK) or (action == ACTION_SELECT) or (action == ACTION_SHOW_INFO): xbmcgui.Window(10000).setProperty('reminders', '0') tools.writeLog('Display of notifications aborted by user', level=xbmc.LOGNOTICE) self.close()
def _xmlToDict(self, xmlText): xmlDict = {} itemlist = ET.fromstring(xmlText) for child in itemlist: xmlDict[child.tag] = child.text tools.writeLog('xmlDict = ' + str(xmlDict)) return xmlDict
def getfolderlastmtime(folderpath): ''' 获取文件夹中最后修改的文件名称和时间,用于网闸同步监控,不检查子文件夹 参数:folderpath 文件名 返回值:文件名称 string , 最后修改时间 datetime ,检查结果:0 正常,1 异常 ''' filelastmtime = None filelastmname = None fileflag = 1 # 初始化标志 # 如果不是文件夹,立刻返回 if not os.path.isdir(folderpath): return filelastmname, filelastmtime, fileflag # 遍历文件 for filename in os.listdir(path=folderpath): filepathstr = os.path.join(folderpath, filename) # 判断是文件再干活 if os.path.isfile(filepathstr): if fileflag == 1 : fileflag = 0 filelastmtime = datetime.datetime.fromtimestamp(os.stat(filepathstr).st_mtime) filelastmname = filepathstr continue if datetime.datetime.fromtimestamp(os.stat(filepathstr).st_mtime) > filelastmtime: filelastmtime = datetime.datetime.fromtimestamp(os.stat(filepathstr).st_mtime) filelastmname = filepathstr tools.writeLog('网闸[' + folderpath + ']下最后修改的文件名称:' + os.path.basename(filelastmname) + ' ;最后修改时间为:' + str(filelastmtime)) return filelastmname, filelastmtime, fileflag
def splitOGGlog(filepath, splitstr, splitstrtime=' at '): ''' 传入OGG日志文件路径和分隔符,解析出trail最后序列号和最后文件读取时间 ''' trailfilenumber = None # trail文件序号 trailfiletime = None # trail文件读取时间 # 读取文件 try: with open(filepath, encoding='UTF-8') as sourcefile: # line_number=0 for a_line in sourcefile: # line_number += 1 if 'Opened trail file' in a_line: # print('{:>4}{}'.format(line_number,a_line.rstrip())) trailfilenumber = a_line[a_line.index(splitstr) + len(splitstr):a_line.index(' at ' )] trailfiletime = a_line[a_line.index(' at ') + 4:-1] except: tools.writeLog(filepath + '文件不存在啊,赶快处理啊!') # raise ValueError(filepath + '文件不存在啊,赶快处理啊!') #不报错,而是返回错误代码 return 0000, 'OGG日志文件异常' tools.writeLog('最后文件序号:' + str(trailfilenumber) + ' 最后更新时间:' + str(trailfiletime)) return trailfilenumber, trailfiletime
def send_head(self, text): self.send_response(200) self.send_header("Content-type", 'text/html') fullLength = len(text) tools.writeLog('fullLength, text = ' + str(fullLength) + str(text)) self.send_header("Content-Length", str(fullLength)) self.end_headers() return
def onInit(self): tools.writeLog('Init notification window') self.getControl(DialogKaiToast.AVATAR_ID).setImage(self.icon) self.getControl(DialogKaiToast.LABEL_1_ID).addLabel(self.label_1) try: self.getControl(DialogKaiToast.LABEL_2_ID).setText(self.label_2) self.getControl(DialogKaiToast.LABEL_2_ID).addLabel(self.label_2) except: self.getControl(DialogKaiToast.LABEL_2_ID).addLabel(self.label_2)
def responseXML(self, dataDict): if dataDict: text = RESPONSE_TEXT_TEMPLATE for key, value in list(dataDict.items()): parameter = '{%s}' % key text = text.replace(parameter, value) tools.writeLog('自己构建的返回信息:' + str(text)) else: text = '' return text
def do_POST(self): if not self.verifyWeixinHeader(): return data = self.rfile.read(int(self.headers['content-length'])) tools.writeLog('data = ' + str(data)) self.send_response(200) self.end_headers() worker = msgHandler(data) self.wfile.write(worker.response().encode('UTF-8'))
def downloadfile(cmdstr): ''' 传入下载命令,通过putty工具进行下载 ''' tools.writeLog('传输FTP日志:开始') # 更改本地目录到psftp工具的路径 localpath = tools.readconfig('dealOGGlog', 'localPath') os.chdir(localpath) # 下载 os.system(cmdstr) tools.writeLog('传输FTP日志:结束')
def updateSliderWindow(self, val=None): if val is not None: self.getControl(SliderWindow.SLIDER_ID).setPercent(val) self.curValue = val t.writeLog('set slider value to %s percent' % (val), xbmc.LOGDEBUG) self.retValue = (self.getControl(SliderWindow.SLIDER_ID).getPercent() * 20.0) / 100 + 8 self.getControl(SliderWindow.SLIDERVAL_ID).setLabel( '{:0.1f}'.format(self.retValue) + ' °C'.decode('utf-8'))
def domyjob(): ''' 调度后台查询任务,开始干活 返回:查询结果 string类型 ''' global LASTDONETIME # 检查命令间隔时间,如果过于频繁,将不执行命令 if datetime.datetime.now() >= LASTDONETIME + datetime.timedelta(seconds=INTERVALTIME): tools.writeLog('收到命令,开始干活!') LASTDONETIME = datetime.datetime.now() return jobww.dojobww() else: tools.writeLog('收到命令过于频繁,停止干活!') return '抱歉,查询过于频繁,请稍等!'
def do_GET(self): print (threading.currentThread().getName()) print (self.path) text = 'This is a webservice for weixin!\n' if self.verifyWeixinHeader(): if self.path.startswith('/update?'): #update_function_module() text = 'updated' elif self.path.startswith('/updatelocal?'): #update_function_module('local') text = 'updated' else: text = self.receivedParams['echostr'] self.sendResponse(text.encode()) tools.writeLog('接收到get请求!') return
def onAction(self, action): t.writeLog('Action received: ID %s' % str(action.getId())) val = None if (action == ACTION_PREVIOUS_MENU) or (action == ACTION_NAV_BACK) or ( action == ACTION_SELECT): self.close() else: if action == ACTION_LEFT or ACTION_RIGHT: Slider = self.getControl(SliderWindow.SLIDER_ID) currentSliderValue = Slider.getPercent() if abs(currentSliderValue - self.curValue) < SliderWindow.SLIDERSTEP: if action == ACTION_LEFT and currentSliderValue >= SliderWindow.SLIDERSTEP: val = self.curValue - SliderWindow.SLIDERSTEP elif action == ACTION_RIGHT and currentSliderValue <= 100 - SliderWindow.SLIDERSTEP: val = self.curValue + SliderWindow.SLIDERSTEP self.updateSliderWindow(val)
def onInit(self): tools.writeLog('Init notification window') self.getControl(DialogKaiToast.AVATAR_ID).setImage(self.icon) try: if hasattr(self.getControl(DialogKaiToast.LABEL_1_ID), 'addLabel'): self.getControl(DialogKaiToast.LABEL_1_ID).addLabel( self.label_1) elif hasattr(self.getControl(DialogKaiToast.LABEL_1_ID), 'setText'): self.getControl(DialogKaiToast.LABEL_1_ID).setText( self.label_1) else: pass if hasattr(self.getControl(DialogKaiToast.LABEL_2_ID), 'addLabel'): self.getControl(DialogKaiToast.LABEL_2_ID).addLabel( self.label_2) elif hasattr(self.getControl(DialogKaiToast.LABEL_2_ID), 'setText'): self.getControl(DialogKaiToast.LABEL_2_ID).setText( self.label_2) else: pass except AttributeError, e: tools.writeLog( 'could not set all attributes to DialogKaiToast properly', xbmc.LOGFATAL) tools.writeLog(e.message, xbmc.LOGFATAL)
def dojobww(): # 邮件正文模板 maildata = '''系统运行状态: [系统运行结果] -------------------------- 1.外网房源标注同步: [状态1] OGG最后处理时间: [trial时间] 2.外网网闸:[网闸状态2] 最后同步时间:[网闸同步时间2] -------------------------- 最后检查时间: [检查时间]''' tools.writeLog('----------外网监控任务:开始!----------') #1 检查外网房源标注OGG运行状态 delaydays = tools.readconfig('dealOGGlog', 'delaydays_r_i_ba') oggresult = dealOGGlogfile.getcheckOGGr_i_ba(int(delaydays)) #2 检查外网网闸工作状态 gappathww = tools.readconfig('gap', 'shuiwu_nankang_gap_path') gapdaysww = tools.readconfig('gap', 'shuiwu_nankang_gap_time') gapresultww = dealgapfile.checkgap(gappathww, int(gapdaysww)) # 根据监控结果,编写邮件正文内容 #1 外网OGG状态 if oggresult[0] == 0: maildata = maildata.replace('[状态1]', '正常') maildata = maildata.replace('[trial时间]', oggresult[1]) else: maildata = maildata.replace('[状态1]', '异常') maildata = maildata.replace('[trial时间]', '异常') #2 外网网闸 if gapresultww[0] == 0: maildata = maildata.replace('[网闸状态2]', '正常') maildata = maildata.replace('[网闸同步时间2]', gapresultww[1]) elif gapresultww[0] == 1: maildata = maildata.replace('[网闸状态2]', '异常') maildata = maildata.replace('[网闸同步时间2]', gapresultww[1]) else: maildata = maildata.replace('[网闸状态2]', '异常') maildata = maildata.replace('[网闸同步时间2]', '未找到数据') # 系统整体运行状态 if oggresult[0] == 0 and gapresultww[0] == 0: maildata = maildata.replace('[系统运行结果]', '全部正常!') else: maildata = maildata.replace('[系统运行结果]', '发生异常!') maildata = maildata.replace('[检查时间]', tools.nowtime()) tools.writeLog('外网监控结果:\n' + maildata) tools.writeLog('----------外网监控任务:结束!----------') return maildata
def splitOGGlog(filepath, splitstr, splitstrtime=' at '): ''' 传入OGG日志文件路径和分隔符,解析出trail最后序列号和最后文件读取时间 ''' trailfilenumber = None # trail文件序号 trailfiletime = None # trail文件读取时间 # 读取文件 try: with open(filepath, encoding='UTF-8') as sourcefile: # line_number=0 for a_line in sourcefile: # line_number += 1 if 'Opened trail file' in a_line: # print('{:>4}{}'.format(line_number,a_line.rstrip())) trailfilenumber = a_line[a_line.index(splitstr) + len(splitstr):a_line.index(' at ')] trailfiletime = a_line[a_line.index(' at ') + 4:-1] except: tools.writeLog(filepath + '文件不存在啊,赶快处理啊!') # raise ValueError(filepath + '文件不存在啊,赶快处理啊!') #不报错,而是返回错误代码 return 0000,'OGG日志文件异常' tools.writeLog('最后文件序号:' + str(trailfilenumber) + ' 最后更新时间:' + str(trailfiletime)) return trailfilenumber, trailfiletime
def checkgap(gappath, gapsyndays): ''' 根据网闸文件最后修改时间检查网闸工作情况 返回值:result: 0-正常,1-有过同步,但异常 , 2-网闸目录不存在,或者目录下没有文件 ; 最后修改时间 string ''' result = getfolderlastmtime(gappath) # 有结果的话,进行时间判断 if result[2] != 1 : legalday = datetime.datetime.now() - datetime.timedelta(days=gapsyndays) if result[1] <= legalday: tools.writeLog('网闸[' + gappath + ']检查完毕,结果:异常') return 1,result[1].strftime('%Y-%m-%d %H:%M:%S') # 异常,需处理 else: tools.writeLog('网闸[' + gappath + ']检查完毕,结果:正常') return 0,result[1].strftime('%Y-%m-%d %H:%M:%S') # 没问题 else: tools.writeLog('网闸文件夹下没文件,异常!') return 2,result[1]
def checkOGGLogfile(trailfiletime, delaydays): ''' delaydays为最大延迟天数,当超过该天数后,认定时间失败 根据trail最后处理时间进行判断:0-正常 , 1-异常 ''' # 解析文件,判断最后接收时间是否在可接受范围内 # legalday = datetime.datetime.now() - datetime.timedelta(days=delaydays) try: trailfiletime = datetime.datetime.strptime(trailfiletime, '%Y-%m-%d %H:%M:%S') except: tools.writeLog('检查文件过程异常,检查结果:异常!') return 1 # 异常,需处理 if trailfiletime <= legalday: tools.writeLog('检查文件完成,检查结果:异常!') return 1 # 异常,需处理 else: tools.writeLog('检查文件完成,检查结果:正常!') return 0 # 没问题
# -*- coding: UTF-8 -*- ''' Created on 2015-3-27 2015 @author: zjc ''' import time import tools logpath = 'E:\\python\\log\\testpython.log' # time.sleep(2) tools.writeLog('替换文件开始!') try: with open('E:\\python\\结果.xls', encoding='GBK') as sourcefile: sourcedata = sourcefile.read() except: tools.writeLog('文件不存在啊,赶快处理啊!') raise ValueError('文件不存在啊,赶快处理啊!') with open('E:\\python\\结果_替换后.xls', 'w') as targetfile: tools.writeLog('开始重写文件!') targetfile.write(sourcedata.replace('charset=UTF-8', 'charset=GBK')) tools.writeLog('替换文件顺利结束!')
def close(self): BaseWindow.close(self) tools.writeLog('Close notification window')
def onClick(cls, controlID): tools.writeLog('click received: ID %s' % (controlID))
def close(self): BaseWindow.close(self) t.writeLog('Close slider window')
def verifyWeixinHeader(self): self.receivedParams = self.requestGet() tools.writeLog('接受到的参数为:' + str(self.receivedParams)) return (self.receivedParams and self.isWeixinSignature())
def onInit(self): t.writeLog('Init slider window', xbmc.LOGDEBUG) self.getControl(SliderWindow.LABEL_ID).setLabel(self.label) self.updateSliderWindow(val=self.initValue)
def close(self): BaseWindow.close(self) t.writeLog('Close slider window', xbmc.LOGDEBUG)