def sendMsgtoDingDing(mydict, sendgroup, msg): body = { "msgtype": "link", "link": { "text": "群机器人是钉钉群的高级扩展功能。", "title": "服务器状态信息", "picUrl": "", "messageUrl": "http://47.91.157.89:999/" } } headers = {'content-type': "application/json"} url = sendgroup[mydict][2] body['link']["text"] = msg body['link']["messageUrl"] = sendgroup[mydict][3] response = requests.post(url, data=json.dumps(body), headers=headers) res = eval(response.text) # eval 转为字典,不能防注入 if (response.status_code == 200) and (res['errcode'] == 0): tools.recordLog('DingDingCode:' + mydict + ' ' + str(res['errcode']) + ':' + res['errmsg']) print(res['errmsg']) return 0 #发送成功 else: tools.recordLog('DingDingCode:' + mydict + ' ' + str(res['errcode']) + ':' + res['errmsg']) print(res['errmsg']) return int(res['errcode']) #未发送或发送失败
def msgPlan(msg, plan, fuwu): if (len(msg) < 2) and (plan == 1): print('计划扫描,所有服务器状态正常,按计划发送报告') msg = '计划扫描: ' + fuwu + ' 所有服务器状态正常' tools.recordLog(msg) elif (len(msg) < 2) and (plan == 0): print('定时扫描:' + fuwu + ' 所有服务器状态正常,不发送报警') msg = '' tools.recordLog('定时扫描:' + fuwu + ' 所有服务器状态正常,不发送报警') return msg
def readConfig(group,key): cp = configparser.SafeConfigParser() value ="" try: cp.read('config.ini',encoding='utf-8') value = eval(cp.get(group,key)) except Exception as err: tools.recordLog("read config err!"+ str(err)) print("read config err!"+ str(err)) return value
def health(plan=1): #导入config配置文件 ip=configRead.readConfig('server','ip') sites=list(ip.keys()) logging.debug(sites) infomationList = [] #搜集各服务器状态生成到这个list #收集各服务器状态信息 for i in range(len(sites)): #print(sites[i]) #取得各台子的名称 taiziStr = sites[i] for j in range(len(ip[sites[i]])): functionStr =ip[sites[i]][j][0] for k in range(1,len(ip[sites[i]][j])): line=[] url = r'http://'+ip[sites[i]][j][k]+r':9999/?key=getinfo' line.append(taiziStr) line.append(functionStr) line.append(ip[sites[i]][j][k]) line = line + list(getServerInfo.getStatus(url)) infomationList.append(line) print('.') #收集并发送报警 dingdingAlarmDict = getAlarm.getAlarmDict(infomationList) code = DingDingRobot.sendAlarm(dingdingAlarmDict,plan) tools.recordLog(str(getAlarm.getAlarmDict(infomationList))) #报警数据上色,生成html infomationList1= htmlAlarm.color(infomationList,0) #上色 htmlfile = configRead.readConfig('parameter','webfile') tools.writelisttohtml(infomationList1,htmlfile) #生成html infomationList2= htmlAlarm.color(infomationList,1) #上色,带升级链接 htmlfile = configRead.readConfig('parameter','webupdatefile') tools.writelisttohtml(infomationList2,htmlfile) #生成html logging.debug('End of program'.center(30,'-'))
def _getLogger(self): this_file = inspect.getfile(inspect.currentframe()) dirpath = os.path.abspath(os.path.dirname(this_file)) handler = logging.FileHandler(os.path.join(dirpath, "service.log")) formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) tools.recordLog(str(handler)) return ""
def getPath(): #获取服务执行程序的路径 try: key = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\ServerStatus") downloadPath = winreg.QueryValueEx(key, "ImagePath") path = os.path.dirname(downloadPath[0][1:]) except Exception as err: path = r'c:\windows\system32' tools.recordLog('Path change err: ' + str(err)) return path
def getsqlServer(): #导入config配置文件 sqlServerList = configRead.readConfig('DB', 'sqlserver') syncinfo = [] line = [] #print(sqlServerList) for i in sqlServerList['sync']: line.append(i[0]) try: line.append(str(syncsql.getSyncSeconds(i))) except Exception as err: print(str(err)) line = 'can\'t get info' tools.recordLog(str(err)) syncinfo.append(line) line = [] tools.recordLog(str(syncinfo)) htmlfile = configRead.readConfig('parameter', 'syncfile') tools.writelisttohtml(syncinfo, htmlfile) #生成html
def msgPlan(msg, plan, fuwu): if (len(msg) < 2) and (plan == 1): print('计划扫描,所有服务器状态正常,按计划发送报告') if fuwu == 'ECSHEALTH': msg = '' tools.recordLog('ECSHEALTH 暂没有ECS到期,无需报警') else: tools.recordLog('计划扫描: ' + fuwu + ' 所有服务器状态正常') elif (len(msg) < 2) and (plan == 0): print('定时扫描:' + fuwu + ' 所有服务器状态正常,不发送报警') msg = '' tools.recordLog('定时扫描:' + fuwu + ' 所有服务器状态正常,不发送报警') return msg
def timeCheck(sendgroup, mydict): #sendgroup = configRead.readConfig('dingding','sendgroup') runTime = sendgroup[mydict][5] print(runTime) currentTime = tools.get_hour() print(currentTime) #在允许的时间段内扫描 if (currentTime >= runTime[0]) and (currentTime <= runTime[1]): print(mydict + "时间命中") tools.recordLog(mydict + "时间命中") return True else: print(mydict + "时间没命中") tools.recordLog(mydict + "时间没有命中") tools.recordLog("runTime0" + runTime[0]) tools.recordLog("runTime1" + runTime[1]) print("runTime0" + runTime[0]) print("runTime1" + runTime[1]) return False
def sendAlarm(msgDict, plan): #第一个body 是纯消息,不带链接 #body = {"msgtype": "text","text": {"content": "测试"},"at": {"atMobiles": ["18678966660"], "isAtAll": "false"}} sendgroup = configRead.readConfig('dingding', 'sendgroup') #count判断频率使用 count = int(gl.getvalue('count')) + 1 gl.setvalue('count', str(count)) print('count=' + str(count)) tools.recordLog('count=' + str(count)) for mydict in sendgroup.keys(): # (count % int(sendgroup[mydict][4]))==0 是执行频率 ,例如运维群每5分钟通知一次,那sendgroup[mydict][4]=5就好 print(mydict + ' 频率: ' + sendgroup[mydict][4]) if timeCheck(sendgroup, mydict) == False: continue print(mydict + ' 尝试' + 'plan=' + str(plan)) print('count=' + str(count) + '余数:' + str((count % int(sendgroup[mydict][4])))) #以下判断,当plan=1时,无条件执行扫描 if ((sendgroup[mydict][0].upper() == 'ON') and ((count % int(sendgroup[mydict][4])) == 0)) or ( (sendgroup[mydict][0].upper() == 'ON') and (plan == 1)): print(mydict + ' 命中: ' + 'plan=' + str(plan) + '\n') tools.recordLog(mydict + ' 命中: ' + 'plan=' + str(plan)) tools.recordLog('count=' + str(count) + ' 命中' + str((count % int(sendgroup[mydict][4])))) if sendgroup[mydict][1].upper() == 'SERVERHEALTH': msg = msgDict['ServerHealth'] elif sendgroup[mydict][1].upper() == 'SEVICEHEALTH': msg = msgDict['SeviceHealth'] elif sendgroup[mydict][1].upper() == 'ECSHEALTH': msg = msgDict['ECSHealth'] msg = msgPlan(msg, plan, sendgroup[mydict][1].upper()) sendMsgtoDingDing(mydict, sendgroup, msg)
def sendAlarm(msg): body = { "msgtype": "text", "text": { "content": "测试" }, "at": { "atMobiles": ["18678966660"], "isAtAll": "false" } } headers = {'content-type': "application/json"} if len(msg) < 2: print('报警数据为空!') msg = '所有服务器状态正常' tools.recordLog(msg) body['text']["content"] = msg url = configRead.readConfig('dingding', 'url') body['at']["atMobiles"] = configRead.readConfig('dingding', 'atMobiles') # 这里有个细节,如果body需要json形式的话,需要做处理 # 可以是data = json.dumps(body) response = requests.post(url, data=json.dumps(body), headers=headers) # 也可以直接将data字段换成json字段,2.4.3版本之后支持 #print(response['errmsg']) res = eval(response.text) # eval 转为字典,不能防注入 if (response.status_code == 200) and (res['errcode'] == 0): tools.recordLog('DingDingCode:' + str(res['errcode']) + ':' + res['errmsg']) return 0 #发送成功 else: tools.recordLog('DingDingCode:' + str(res['errcode']) + ':' + res['errmsg']) return 1 #发送失败
def SvcDoRun(self): tools.recordLog("Service start") time2 = 0 timeCha = 0 #执行扫描的时间差 mingzhongtime = '' while self.run: tools.recordLog("Server status " + gl.getvalue('version') + ' is running at ' + tools.get_time_stamp()) tools.recordLog("这是服务器启动后的开始") #gl.setvalue('count','0') sleepsecond = configRead.readConfig('parameter', 'sleepsecond') runtime = configRead.readConfig('parameter', 'runtime') print(sleepsecond) print(runtime) tools.recordLog(str(sleepsecond)) tools.recordLog(str(runtime)) currentTime = tools.get_hour() tools.recordLog(str(currentTime)) #开始按计划扫描后,plan=0,以错过本次的周期扫描。当plan还=1时,按定时间隔扫描。 plan = 1 time1 = tools.get_hour() for i in runtime: tools.recordLog(str(tools.time_cmp(currentTime, i))) tools.recordLog(str(i)) print("计划扫描时间" + i) print('时间差1:' + str(timeCha)) if tools.time_cmp(currentTime, i) < (int(sleepsecond) + int(timeCha)): tools.recordLog("计划扫描命中:" + i) print("计划扫描命中:" + i) print("上次命中计划:" + mingzhongtime) if i != mingzhongtime: print('currentTime=' + currentTime) print("上次命中计划:" + mingzhongtime) ServerHealth.health(plan) # 1 参数为计划扫描 plan = 0 mingzhongtime = i if plan == 1: print("周期扫描命中" + currentTime) tools.recordLog("周期扫描命中" + currentTime) ServerHealth.health(0) # 0 参数为周期扫描 time2 = tools.get_hour() timeCha = tools.time_cmp(time1, time2) print('时间差2:' + str(timeCha)) time.sleep(int(sleepsecond))
def health(plan=1): infomationList = getServerinfo() #过滤服务器状态报警 dingdingAlarmDict = getAlarm.getAlarmDict(infomationList) dingdingAlarmDict.setdefault('ECSHealth', '') #收集阿里服务器到期日报警 #获取当前时间 # escAlarmTime = configRead.readConfig('aliyun', 'AlarmTime') currentTime = tools.get_hour() print(currentTime) print(escAlarmTime) if ((currentTime >= escAlarmTime[0]) and (currentTime <= escAlarmTime[1])): print('ECS报警时段命中') print('报警时段:' + escAlarmTime[0] + escAlarmTime[1]) currentDay = tools.get_day() print(currentDay) print(gl.getvalue('escSendday')) tools.recordLog('ECS报警时段命中') tools.recordLog(currentDay) tools.recordLog(gl.getvalue('escSendday')) if currentDay != gl.getvalue('escSendday'): print('ECS收集,天不同') tools.recordLog('ECS收集信息,一天只能一次') try: ecsAlarmList = alarmecs.getAlarmEcs() print(ecsAlarmList) numAlarm = len(ecsAlarmList) print('有' + str(numAlarm) + '台ECS将要到期') tools.recordLog('有' + str(numAlarm) + '台ECS将要到期') except Exception as err: tools.recordLog("alarmecs.getAlarmEcs err : " + str(err)) print(str(err)) if numAlarm > 0: print('ecs报警了') tools.recordLog('ecs>0报警了') gl.setvalue('escSendday', currentDay) dingdingAlarmDict['ECSHealth'] = '有' + str( numAlarm) + '台ECS将要到期' ecslists = ecslist.getEcslist() ecsfile = configRead.readConfig('aliyun', 'ecsfile') tools.writelisttohtml(ecslists, ecsfile) #print('打印MSG 字典') #print(dingdingAlarmDict) DingDingRobot.sendAlarm(dingdingAlarmDict, plan) tools.recordLog(str(dingdingAlarmDict)) #报警数据上色,生成html infomationList1 = htmlAlarm.color(infomationList, 0) #上色 htmlfile = configRead.readConfig('parameter', 'webfile') tools.writelisttohtml(infomationList1, htmlfile) #生成html infomationList2 = htmlAlarm.color(infomationList, 1) #上色,带升级链接 htmlfile = configRead.readConfig('parameter', 'webupdatefile') tools.writelisttohtml(infomationList2, htmlfile) #生成html getsqlServer() tools.recordLog('同步数据获取完毕') logging.debug('End of program'.center(30, '-'))
def quitgame(words): global kid global speak kid.endTime = tools.get_hour() kid.wronglist = list(set(kid.wronglist)) #去除重复单词 wrongTime = len(kid.wronglist) rightTime = kid.question - wrongTime print('得分 = ' + str(round((rightTime - 1) / (kid.question - 1) * 100, 0))) print('\n总共出题:' + str(kid.question - 1)) print('答对题目:' + str(rightTime - 1)) print('答错题目:' + str(wrongTime)) print('提示次数:' + str(kid.alarmTime)) kid.spendMinute = round(tools.time_cmp(kid.endTime, kid.startTime) / 60, 0) kid.spendSecond = tools.time_cmp(kid.endTime, kid.startTime) % 60 print('用时:' + str(kid.spendMinute) + '分' + str(kid.spendSecond) + '秒') speak.Speak('你总共得分:' + str(round((rightTime - 1) / (kid.question - 1) * 100, 0)) + '分') if len(kid.wronglist) > 0: print('\n以下是答错的单词') speak.Speak('你答错了下面的单词:') pprint.pprint(kid.wronglist) time.sleep(5) print('\n') rewrite(kid.wronglist, words) else: if (kid.question - 1) > 0: print('恭喜你全部正确!\n') speak.Speak('恭喜你全部正确!') tools.recordLog('得分 = ' + str(round((rightTime - 1) / (kid.question - 1) * 100, 0))) tools.recordLog('总共出题:' + str(kid.question - 1)) tools.recordLog('答对题目:' + str(rightTime - 1)) tools.recordLog('答错题目:' + str(wrongTime)) tools.recordLog('提示次数:' + str(kid.alarmTime)) tools.recordLog('用时:' + str(kid.spendMinute) + '分' + str(kid.spendSecond) + '秒') tools.recordLog('以下是答错的单词') tools.recordLog(str(kid.wronglist)) print('\n练习完毕,请输入回车退出') while len(input()) < 1: sys.exit(0)
def listenWrite(words, questionnum=10): global kid global speak kid.startTime = tools.get_hour() if questionnum > len(words): tools.recordLog("出题数目大于单词总量") print("出题数目大于单词总量,将使用最大单词量") inputPress = '' tools.recordLog('') tools.recordLog('全新答题开始:') for i in words: kid.question = kid.question + 1 if kid.question > questionnum: quitgame(words) while inputPress != 'Q': print("\n第" + str(kid.question) + "题,请根据发音输入答案:", end='') speak.Speak("第" + str(kid.question) + "题") #time.sleep(1) try: playsound.playsound(i['mp3'], True) except Exception as err: tools.recordLog(str(err)) tools.recordLog("打开MP3出错") print("打开MP3出错") sys.exit(0) inputPress = input() inputPress = inputPress.strip().upper() if inputPress == i['word'].upper(): print('回答正确!') break elif inputPress == 'A' or inputPress == '': time.sleep(1) continue elif inputPress == 'S': kid.alarmTime = kid.alarmTime + 1 print("正确的单词:" + i['word']) kid.wronglist.append(i['word']) time.sleep(1) continue elif inputPress == 'Q': quitgame(words) else: tools.recordLog("第" + str(kid.question) + "题 " + i['word'] + ' 回答错误:' + inputPress) print(inputPress.lower() + '是错误的 ! 请再听一次') kid.wronglist.append(i['word']) print("该单词的含义:" + i['mean']) quitgame(words)
## if i!=mingzhongtime: ## print('currentTime='+currentTime) ## print("上次命中计划:"+mingzhongtime) ## ServerHealth.health(plan) # 1 参数为计划扫描 ## plan=0 ## mingzhongtime=i ## ## ## if plan==1: ## print("周期扫描命中"+currentTime) ## tools.recordLog("周期扫描命中"+currentTime) ## ServerHealth.health(0) # 0 参数为周期扫描 ## ## time2=tools.get_hour() ## timeCha = tools.time_cmp(time1,time2) ## print('时间差2:'+str(timeCha)) ## time.sleep(int(sleepsecond)) if len(sys.argv) == 1: try: evtsrc_dll = os.path.abspath(servicemanager.__file__) servicemanager.PrepareToHostSingle(Serversinfo) servicemanager.Initialize('Serversinfo', evtsrc_dll) servicemanager.StartServiceCtrlDispatcher() except win32service.error as details: tools.recordLog(str(details)) print(str(details)) pass else: win32serviceutil.HandleCommandLine(Serversinfo)
time_stamp = "%s.%03d" % (data_head, data_secs) return time_stamp def get_hour(): ct = time.time() local_time = time.localtime(ct) hourtime = time.strftime("%H:%M:%S", local_time) return hourtime def time_cmp(first_time, second_time): if first_time < second_time: first_time, second_time = second_time, first_time return (datetime.datetime.strptime(first_time, "%H:%M:%S") - datetime.datetime.strptime(second_time, "%H:%M:%S")).seconds sleepsecond = configRead.readConfig('parameter', 'sleepsecond') runtime = configRead.readConfig('parameter', 'runtime') currentTime = tools.get_hour() tools.recordLog(str(tools.time_cmp(currentTime, i))) print('sleepsecond=' + str(sleepsecond)) print(runtime) for i in runtime: if tools.time_cmp(currentTime, i) < sleepsecond: print("运行时间到了") else: print("未到运行时间")
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.run = False tools.recordLog("Service stop ...")
line.append(taiziStr) line.append(functionStr) line.append(ip[sites[i]][j][k]) line = line + list(getServerInfo.getStatus(url)) infomationList.append(line) print('.') #收集并发送报警 dingdingAlarmtxt = getAlarm.getAlarmstr(infomationList) code = DingDingRobot.sendAlarm(dingdingAlarmtxt) if code==0: print('send alarm ok!') tools.recordLog('send alarm ok!') else: print('send err !') tools.recordLog('send alarm err!') tools.recordLog(getAlarm.getAlarmstr(infomationList)) #报警数据上色,生成html infomationList= htmlAlarm.color(infomationList) #上色 tools.listtohtml(infomationList) #生成html
def sendAlarm(msgDict, plan): #第一个body 是纯消息,不带链接 #body = {"msgtype": "text","text": {"content": "测试"},"at": {"atMobiles": ["18678966660"], "isAtAll": "false"}} body = { "msgtype": "link", "link": { "text": "群机器人是钉钉群的高级扩展功能。", "title": "服务器状态信息", "picUrl": "", "messageUrl": "http://47.91.157.89:999/" } } headers = {'content-type': "application/json"} sendgroup = configRead.readConfig('dingding', 'sendgroup') count = int(gl.getvalue('count')) + 1 gl.setvalue('count', str(count)) print('count=' + str(count)) tools.recordLog('count=' + str(count)) for mydict in sendgroup.keys(): # (count % int(sendgroup[mydict][4]))==0 是执行频率 ,例如运维群每5分钟通知一次,那sendgroup[mydict][4]=5就好 print(mydict + ' 频率: ' + sendgroup[mydict][4]) runTime = sendgroup[mydict][5] print(runTime) currentTime = tools.get_hour() print(currentTime) #在允许的时间段内扫描 if (currentTime >= runTime[0]) and (currentTime <= runTime[1]): print("时间命中") tools.recordLog("时间命中") else: print("时间没命中") tools.recordLog("时间没有命中") tools.recordLog("runTime0" + runTime[0]) tools.recordLog("runTime1" + runTime[1]) print("runTime0" + runTime[0]) print("runTime1" + runTime[1]) continue print(mydict + ' 尝试' + 'plan=' + str(plan)) print('count=' + str(count) + '余数:' + str((count % int(sendgroup[mydict][4])))) #以下判断,当plan=1时,无条件执行扫描 if ((sendgroup[mydict][0].upper() == 'ON') and ((count % int(sendgroup[mydict][4])) == 0)) or ( (sendgroup[mydict][0].upper() == 'ON') and (plan == 1)): print(mydict + ' 命中: ' + 'plan=' + str(plan)) tools.recordLog(mydict + ' 命中: ' + 'plan=' + str(plan)) tools.recordLog('count=' + str(count) + ' 命中' + str((count % int(sendgroup[mydict][4])))) if sendgroup[mydict][1].upper() == 'SERVERHEALTH': msg = msgDict['ServerHealth'] else: msg = msgDict['SeviceHealth'] msg = msgPlan(msg, plan, sendgroup[mydict][1]) url = sendgroup[mydict][2] body['link']["text"] = msg body['link']["messageUrl"] = sendgroup[mydict][3] response = requests.post(url, data=json.dumps(body), headers=headers) res = eval(response.text) # eval 转为字典,不能防注入 if (response.status_code == 200) and (res['errcode'] == 0): tools.recordLog('DingDingCode:' + mydict + ' ' + str(res['errcode']) + ':' + res['errmsg']) print(res['errmsg']) return 0 #发送成功 else: tools.recordLog('DingDingCode:' + mydict + ' ' + str(res['errcode']) + ':' + res['errmsg']) print(res['errmsg']) return int(res['errcode']) #未发送或发送失败