def getAlarmstr(infomationList): cpuAlarm = int(configRead.readConfig('alarm', 'cpuAlarm2')) # CPU 利用率超70%报警 memAlarm = int(configRead.readConfig('alarm', 'memAlarm2')) # MEM 利用率超70%报警 diskAlarm1 = int(configRead.readConfig('alarm', 'diskAlarm1')) # 磁盘 剩余空间低于30G 报橙色警 diskAlarm2 = int(configRead.readConfig('alarm', 'diskAlarm2')) # 磁盘 剩余空间低于10G 报红色警 alarmLine = [] alarmList = [] timeOut = configRead.readConfig('parameter', 'timeout') timeOutStr = '超时 time >' + str(timeOut) for line in infomationList: if line[3] == timeOutStr: alarmLine.append(line[0]) alarmLine.append(line[1]) alarmLine.append(line[2]) alarmLine.append(str(timeOut) + '秒超时') alarmList.append(alarmLine) alarmLine = [] continue if int(line[4]) > cpuAlarm: alarmLine.append(line[0]) alarmLine.append(line[1]) alarmLine.append(line[2]) alarmLine.append('CPU=' + line[4]) alarmList.append(alarmLine) alarmLine = [] if int(line[5]) > memAlarm: alarmLine.append(line[0]) alarmLine.append(line[1]) alarmLine.append(line[2]) alarmLine.append('MEM=' + line[5]) alarmList.append(alarmLine) alarmLine = [] alldisk = line[6].split(' ') for d in alldisk: if d == '': #排除空值 continue disk = d.split(':') diskAvliable = disk[1].split(r'/') if (int(diskAvliable[0]) < diskAlarm2) and (int(diskAvliable[1]) > 6): #剔除光驱 alarmLine.append(line[0]) alarmLine.append(line[1]) alarmLine.append(line[2]) alarmLine.append(disk[0] + '剩余' + diskAvliable[0] + 'G') alarmList.append(alarmLine) alarmLine = [] #组合大字符串 dingdingAlarmTxt = '' for i in alarmList: dingdingAlarmTxt = dingdingAlarmTxt + i[0] + ' ' + i[1] + ':\n ' + i[ 2] + ' ' + i[3] + '\n' return dingdingAlarmTxt
def getUrl(url): #检测url给出状态反馈 timeOut = int(configRead.readConfig('timeout')) try: res = requests.get(url, timeout=timeOut) except Exception as err: return ["超时 time >" + str(timeOut), "", "", ""] try: display = res.json() except Exception as err: return ["无法连接", "", "", ""] cpuAlarm = int(configRead.readConfig('cpuAlarm')) # CPU 利用率超70%报警 memAlarm = int(configRead.readConfig('memAlarm')) # MEM 利用率超70%报警 diskAlarm1 = int(configRead.readConfig('diskAlarm1')) # 磁盘 剩余空间低于30G 报橙色警 diskAlarm2 = int(configRead.readConfig('diskAlarm2')) # 磁盘 剩余空间低于30G 报红色警 sysinfo = '' syslist = [] disktmp = '' if 'CPU' in display.keys(): syslist.append(display['CPU']['CPU核心'] + 'C' + display['Memory']['总内存G'] + 'G') cpu1 = display['CPU']['CPU利用率'].strip('%') if int(cpu1) > cpuAlarm: cpu1 = '<font color=red>' + cpu1 + '</font>' mem1 = display['Memory']['内存利用率'].strip('%') if int(mem1) > memAlarm: mem1 = '<font color=red>' + mem1 + '</font>' syslist.append('CPU=' + cpu1 + '%') syslist.append('MEM=' + mem1 + '%') disktmp = 'DISK: ' logging.debug(sysinfo) logging.debug(display['Disk']) logging.debug(display['Disk'].keys()) for i in display['Disk']: disknum1 = display['Disk'][i][0].strip('G') disknum2 = display['Disk'][i][1].strip('G') if (int(disknum1) < diskAlarm1) and (int(disknum2)) > 20: disknum1 = '<font color=#FF8C00>' + disknum1 + '</font>' elif (int(disknum1) < diskAlarm2) and (int(disknum2)) > 20: disknum1 = '<font color=red>' + disknum1 + '</font>' print(disknum1) diskstr = i + ':' + disknum1 + r'/' + display['Disk'][i][1] + ' ' disktmp = disktmp + diskstr syslist.append(disktmp) syslist.append(display['version']) return syslist try: res.raise_for_status() except Exception as exc: #print('网站不可用:%s' %(exc)) return ["无法连接", "", "", ""]
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 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 getServerinfo(): #导入config配置文件 ip = configRead.readConfig('server', 'ip') #print(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('.') return infomationList
def rewrite(wronglist, words): print("亲爱的,你一共做错了" + str(len(wronglist)) + '个单词\n') practice = int(configRead.readConfig('listenwrite', 'practice')) print('以下开始每一个做错的单词练习输入' + str(practice) + '遍\n\n') for i in wronglist: print(i) #speak.Speak(i.lower()) for j in words: if i == j['word']: print('单词含义:') print(j['mean']) #playsound.playsound(j['mp3'], True) break m = 0 while m < practice: print('\n请输入正确的单词:', end='') playsound.playsound(j['mp3'], True) keyinput = input() if keyinput.strip().lower() != i.lower(): print("输入错误!\n") else: print("输入正确!\n") m = m + 1 print('\n')
def main(): ## Main # # This will take in the required arguments. Find the location of files needed and export all variables to be used in bash scripts # The it will run the first bash script to start the process. # parser = argparse.ArgumentParser() parser.add_argument('-n', help="The number of iterations", default=1) parser.add_argument( '-i', help= "This is the string to identify the output histograms and geometry files", default="DEFAULT") parser.add_argument('-r', help="The run number to align", default="DEFAULT") parser.add_argument( '-o', help="option: End after single run with only XYShifts. 1/0", default="0") args = parser.parse_args() if args.r == "DEFAULT": print "No run number given" print "Use the flag -h to see help" sys.exit(-1) if args.i == "DEFAULT": print "No identifier given" print "Use the flag -h to see help" sys.exit(-1) ##Set the variables to export to bash scripts os.environ["RUN"] = args.r os.environ["numberOfIterations"] = args.n os.environ["outputIdentifier"] = args.i os.environ["singleLoop"] = args.o ##Get the scripts which will actually do the work and location of the example and add to the system path. itScriptLoc = findIterScripts() itScriptLocPython = itScriptLoc + "/pythonScripts" sys.path.append(itScriptLocPython) from configRead import readConfig from findVariable import findVar base = findVar("BasePath") string = str(base[1]).replace(" ", "") string = string.replace('\n', "") os.environ["exampleLocation"] = string vars = readConfig(string) for var in vars: print "var: ", var value = str(checkDollar(var[1])) os.environ[var[0]] = value bashPath = itScriptLoc + "/initialiseAndRun.sh" os.environ["scriptsLocation"] = itScriptLoc print bashPath subprocess.call(bashPath, shell=True)
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 dayIn(days): ecsDays=configRead.readConfig('aliyun','ecsAlarm') if days<ecsDays[-1]: return True for i in ecsDays: if days==i: return True return False
def listtohtmlupdate(mylist): htmlfile = configRead.readConfig('parameter', 'webupdatefile') try: webUrlFile = open(htmlfile, 'w', encoding='utf-8') except Exception as err: recordLog(str(err)) return try: webUrlFile.write(r''' <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <style type=text/css> table.gridtable { font-family: verdana,arial,sans-serif; font-size:14px; color:#333333; border-width: 1px; border-color: #666666; } table.gridtable th { border-width: 1px; padding: 1px; border-style: solid; border-color: #666666; background-color: #dedede; } table.gridtable td { border-width: 1px; padding: 6px; border-style: solid; border-color: #666666; background-color: #ffffff;} </style>''') webUrlFile.write('<h2>' + get_time_stamp() + '</h2>\n') webUrlFile.write('\n<table class=gridtable align=\'left\'>\n') for t1 in mylist: webUrlFile.write('<tr>') for t2 in t1: webUrlFile.write('<td>' + t2 + '</td>') webUrlFile.write('<tr>\n') webUrlFile.write('</table>') except Exception as err: recordLog("write to html error") recordLog(str(err)) finally: webUrlFile.close()
def getAllaccountEcslist(): account=configRead.readConfig('aliyun','account') ecslist=[] ecslists=[] for i in account: print(account[i]) for j in account[i][2]: #client= AcsClient("LTAInYu7Dfx1S4P5","0pbGDxkQcB1AFPl7u5PXaZgas4MyAo","cn-hongkong") client= AcsClient(account[i][0],account[i][1],j) ecslist=getEcs(i,client) ecslists = ecslists + ecslist ecslist=[] return ecslists
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 main(): ## Main # # This will take in the required arguments. Find the location of files needed and export all variables to be used in bash scripts # The it will run the first bash script to start the process. # parser = argparse.ArgumentParser() parser.add_argument('-n', help="The number of iterations", default=1) parser.add_argument('-i', help="This is the string to identify the output histograms and geometry files",default="DEFAULT" ) parser.add_argument('-r', help="The run number to align",default="DEFAULT") parser.add_argument('-o', help="option: End after single run with only XYShifts. 1/0",default="0") args = parser.parse_args() if args.r == "DEFAULT": print "No run number given" print "Use the flag -h to see help" sys.exit(-1) if args.i == "DEFAULT": print "No identifier given" print "Use the flag -h to see help" sys.exit(-1) ##Set the variables to export to bash scripts os.environ["RUN"] = args.r os.environ["numberOfIterations"] = args.n os.environ["outputIdentifier"] = args.i os.environ["singleLoop"] = args.o ##Get the scripts which will actually do the work and location of the example and add to the system path. itScriptLoc=findIterScripts() itScriptLocPython=itScriptLoc + "/pythonScripts" sys.path.append(itScriptLocPython) from configRead import readConfig from findVariable import findVar base=findVar("BasePath") string = str(base[1]).replace(" ","") string = string.replace('\n',"") os.environ["exampleLocation"] = string vars = readConfig(string) for var in vars: print "var: ",var value = str(checkDollar(var[1])) os.environ[var[0]] = value bashPath = itScriptLoc + "/initialiseAndRun.sh" os.environ["scriptsLocation"] = itScriptLoc print bashPath subprocess.call(bashPath, shell=True)
def getStatus(url): #检测url给出状态反馈 timeOut = int(configRead.readConfig('parameter','timeout')) try: res=requests.get(url,timeout=timeOut) except Exception as err: return ["超时 time >"+str(timeOut),"","","",""] try: display =res.json() except Exception as err: return ["无法连接","","",""] sysinfo='' syslist=[] disktmp ='' if 'CPU' in display.keys(): syslist.append(display['CPU']['CPU核心']+'C'+display['Memory']['总内存G']+'G') cpu1 = display['CPU']['CPU利用率'].strip('%') mem1 = display['Memory']['内存利用率'].strip('%') syslist.append(cpu1) syslist.append(mem1) disktmp = '' for i in display['Disk']: disknum1=display['Disk'][i][0].strip('G') disknum2=display['Disk'][i][1].strip('G') print('.',end='') diskstr = i + ':' +disknum1 + r'/'+disknum2+' ' disktmp = disktmp + diskstr syslist.append(disktmp) syslist.append(display['version']) return syslist try: res.raise_for_status() except Exception as exc: #print('网站不可用:%s' %(exc))
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)
gushi = {} line = [] for str1 in gushilines: str1 = str1.strip('\n') str2 = str1.split(',') line.append(str2[2:]) line.append(str2[1]) gushi.setdefault(str2[0], line) line = [] return gushi gushi = readgushi() questionCount = configRead.readConfig('古诗', 'questionnum') #出题数量 questionStr = list(gushi.keys()) #取得古诗名字 answerStr = list(gushi.values()) #取得古诗作者和第一句 zuozhe = [] #作者 for name in answerStr: #取得作者名字的列表 zuozhe.append(name[1]) zuozhe = list(set(zuozhe)) #作者列表去重 zuozheTMP = copy.copy(zuozhe) random.shuffle(questionStr) #随机排列questionStr 列表
volume = filters['volume'] module = '所有单元' if len(filters['module']) > 0: module = filters['module'] print('\n书本选择:' + book) print('年级选择:' + grade) print('上下册选择:' + volume) print('单元选择:' + str(module) + '\n') words = openmyWordBook() #filters={'book':'外语教学与研究出版社','grade':'二年级','volume':'下册','module':[2]} filters = {} filters.setdefault('book', configRead.readConfig('listenwrite', 'book')) filters.setdefault('grade', configRead.readConfig('listenwrite', 'grade')) filters.setdefault('volume', configRead.readConfig('listenwrite', 'volume')) filters.setdefault('module', configRead.readConfig('listenwrite', 'module')) words = filtersMyBook(words, filters) questionnum = configRead.readConfig('listenwrite', 'questionnum') if len(words) < questionnum: question = len(words) else: question = questionnum print('英语小测验 共' + str(question) + '题\n') fanwei(filters)
background-color: #ffffff;} </style>''') webUrlFile.write('\n<table class=gridtable align=\'left\'>\n') for t1 in mylist: webUrlFile.write('<tr>') for t2 in t1: webUrlFile.write('<td>' + t2 + '</td>') webUrlFile.write('<tr>\n') webUrlFile.write('</table>') webUrlFile.close() ip = configRead.readConfig('ip') sites = list(ip.keys()) logging.debug(sites) strInput = '!' infomationList = [] while strInput != '': 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]
def color(infomationList, link=0): cpuAlarm1 = int(configRead.readConfig('alarm', 'cpuAlarm1')) # CPU 利用率超60%报警 cpuAlarm2 = int(configRead.readConfig('alarm', 'cpuAlarm2')) # CPU 利用率超90%报警 memAlarm1 = int(configRead.readConfig('alarm', 'memAlarm1')) # MEM 利用率超70%报警 memAlarm2 = int(configRead.readConfig('alarm', 'memAlarm2')) # MEM 利用率超95%报警 diskAlarm1 = int(configRead.readConfig('alarm', 'diskAlarm1')) # 磁盘 剩余空间低于30G 报橙色警 diskAlarm2 = int(configRead.readConfig('alarm', 'diskAlarm2')) # 磁盘 剩余空间低于10G 报红色警 alarmList = [] timeOut = configRead.readConfig('parameter', 'timeout') timeOut = '超时 time >' + str(timeOut) for line in infomationList: alarmLine = [] alarmLine.append(line[0]) alarmLine.append(line[1]) #link==0,不上链接 if link != 0: alarmLine.append(giveLink(line[2])) alarmLine.append(line[3]) if line[3] == timeOut: alarmList.append(alarmLine) continue CPU = line[4] MEM = line[5] #CPU 报警处理 if int(line[4]) > cpuAlarm1: CPU = giveColor(line[4], 2) elif int(line[4]) > cpuAlarm2: CPU = giveColor(line[4], 1) CPU = 'CPU=' + CPU + '%' alarmLine.append(CPU) #MEM 报警处理 if int(line[5]) > memAlarm1: MEM = giveColor(line[5], 2) elif int(line[5]) > memAlarm2: MEM = giveColor(line[5], 1) MEM = 'MEM=' + MEM + '%' alarmLine.append(MEM) alldisk = line[6].split(' ') diskstr = "DISK: " for d in alldisk: if d == '': #排除空值 continue disk = d.split(':') diskAvliable = disk[1].split(r'/') if (int(diskAvliable[0]) < diskAlarm2) and (int(diskAvliable[1]) > 6): #剔除光驱 diskstr = diskstr + disk[0] + ':' + giveColor( diskAvliable[0], 1) + r'/' + diskAvliable[1] + ' ' elif (int(diskAvliable[0]) < diskAlarm1) and (int(diskAvliable[1]) > 6): #剔除光驱: diskstr = diskstr + disk[0] + ':' + giveColor( diskAvliable[0], 2) + r'/' + diskAvliable[1] + ' ' else: diskstr = diskstr + disk[0] + ':' + diskAvliable[ 0] + r'/' + diskAvliable[1] + ' ' alarmLine.append(diskstr) alarmLine.append(line[7]) alarmList.append(alarmLine) return alarmList
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, '-'))
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 getAlarmDict(infomationList): cpuAlarm = int(configRead.readConfig('alarm', 'cpuAlarm2')) # CPU 利用率超70%报警 memAlarm = int(configRead.readConfig('alarm', 'memAlarm2')) # MEM 利用率超70%报警 diskAlarm1 = int(configRead.readConfig('alarm', 'diskAlarm1')) # 磁盘 剩余空间低于30G 报橙色警 diskAlarm2 = int(configRead.readConfig('alarm', 'diskAlarm2')) # 磁盘 剩余空间低于10G 报红色警 alarmLine = [] alarmList = [] #正常服务器报警列表 alarmStatus = [] #服务器状态服务报警列表 timeOut = configRead.readConfig('parameter', 'timeout') timeOutStr = '超时 time >' + str(timeOut) for line in infomationList: if line[3] == timeOutStr: alarmLine.append(line[0]) alarmLine.append(line[1]) alarmLine.append(line[2]) alarmLine.append('状态服务' + str(timeOut) + '秒超时') alarmStatus.append(alarmLine) alarmLine = [] continue if int(line[4]) > cpuAlarm: alarmLine.append(line[0]) alarmLine.append(line[1]) alarmLine.append(line[2]) alarmLine.append('CPU=' + line[4]) alarmList.append(alarmLine) alarmLine = [] if int(line[5]) > memAlarm: alarmLine.append(line[0]) alarmLine.append(line[1]) alarmLine.append(line[2]) alarmLine.append('MEM=' + line[5]) alarmList.append(alarmLine) alarmLine = [] alldisk = line[6].split(' ') for d in alldisk: if d == '': #排除空值 continue disk = d.split(':') diskAvliable = disk[1].split(r'/') if (int(diskAvliable[0]) < diskAlarm2) and (int(diskAvliable[1]) > 6): #剔除光驱 alarmLine.append(line[0]) alarmLine.append(line[1]) alarmLine.append(line[2]) alarmLine.append(disk[0] + '剩余' + diskAvliable[0] + 'G') alarmList.append(alarmLine) alarmLine = [] #组合大字符串 alarmdict = {} dingdingAlarmTxt1 = '' dingdingAlarmTxt2 = '' for i in alarmList: dingdingAlarmTxt1 = dingdingAlarmTxt1 + i[0] + ' ' + i[1] + ':\n ' + i[ 2] + ' ' + i[3] + '\n' for j in alarmStatus: dingdingAlarmTxt2 = dingdingAlarmTxt2 + j[0] + ' ' + j[1] + ':\n ' + j[ 2] + '\n' + j[3] + '\n' alarmdict.setdefault('ServerHealth', dingdingAlarmTxt1) alarmdict.setdefault('SeviceHealth', dingdingAlarmTxt2) return alarmdict
import configparser import tools #个人常用过程模块,时间,日志 import getAlarm #组织获取报警信息 import DingDingRobot #钉钉报警 import getServerInfo #获取服务器的状态信息 import htmlAlarm #把list中需要报警的数字上色,还是返回list数据 logging.basicConfig(level=logging.DEBUG,format=' %(asctime)s - %(levelname)s - %(message)s') logging.disable(logging.CRITICAL) # 加这句话,就是log全部禁止,不加,就可以log打印了 logging.debug('Start of program'.center(30,'-')) #导入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]])):
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']) #未发送或发送失败