Beispiel #1
0
 def SvcDoRun(self):
     import time
     global httpd
     global port
     self.logger.info("service is run....")
     WebAPI.recordLog("Service start")
     
     while self.run:
         print ("PC Health "+ gl.getvalue('version') + "serving http on port {0}...".format(str(port)))
         WebAPI.recordLog("PC Health "+ gl.getvalue('version') + ' '+ WebAPI.get_time_stamp() + "serving http on port {0}...".format(str(port)))
         try:
             httpd.serve_forever()
         except Exception as err:
             WebAPI.recordLog(str(err))
             WebAPI.recordLog('http server error!')
Beispiel #2
0
def sysInfo():
    info = {}

    line = {}
    line.setdefault('CPU核心', str(psutil.cpu_count()))
    line.setdefault('CPU利用率', str(int(psutil.cpu_percent())) + '%')
    info['CPU'] = line

    line = {}
    line.setdefault(
        '空闲内存G',
        str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0),
                  2)))
    line.setdefault(
        '总内存G',
        str(
            int(
                round(psutil.virtual_memory().total /
                      (1024.0 * 1024.0 * 1024.0)))))
    line.setdefault(
        '内存利用率',
        str(
            int((psutil.virtual_memory().total - psutil.virtual_memory().free)
                / float(psutil.virtual_memory().total) * 100)) + '%')
    info['Memory'] = line

    line = {}

    io = psutil.disk_partitions()
    j = 0
    for i in io:
        diskstr = []
        try:
            o = psutil.disk_usage(i.device)
        except Exception as err:
            logFile = open(r'web.log', 'a')
            logFile.write(get_time_stamp() + '  ')  #写入日志
            logFile.write(str(err) + '\n')  #写入日志
            logFile.close()
            j += 1
            continue

        disk = io[j][0].strip(r':\\')
        diskstr.append(str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G")
        diskstr.append(str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G")
        line.setdefault(disk, diskstr)
        del (diskstr)
        j += 1

    info['Disk'] = line
    try:
        info.setdefault('version', gl.getvalue('version'))
    except Exception as err:
        recordLog("version write err")

    return info
Beispiel #3
0
    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))
Beispiel #4
0
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)
Beispiel #5
0
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, '-'))
Beispiel #6
0
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'])  #未发送或发送失败