#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import sys
import os
import IPy
import pexpect
from multiprocessing import Pool 
import ConfigParser

#version 1.3
#更新返回st号有wrong的问题
#解决返回main(bios)AssertionError问题
#解决返回值为NONE的情况
#NONE为无返回值
## 20170921  加处理日志的东西
## 20171010  添加了升级bios idrac版本的功能
## 20171011  添加了升级bios 添加计划任务的功能
## 20171106  修改了getbiosupdates 在收集信息的时候 将stg和机型也给拿到
## 20171219  关于日志raid和idrac 处理完的结果分割修改成; 分割。
##20180423 增加了获取cpu配置的功能

def operatestg(ip,lines):
    #只返回stg号和设备型号
    for a in  lines:
        st1=re.match('Service Tag.*',a)
        model=re.match('System Model.*\=\s(.*)',a)
        if st1:
            st=re.search('[0-9A-Z]{7}',st1.group()).group()
        if model:
            mode=model.groups()[0].strip()
    if st:
        nstrs = '%s,%s,%s' % (ip,mode,st)
        return nstrs

###Check cpu config
def getCpuInfo(ip,lines):
    #只返回cpu是否开启睿频和性能最大化
    results = []
    results.append(ip)
    for a in  lines:
        SysProfile=re.match('#?SysProfile\=(.*)',a)
        ProcPwrPerf=re.match('#?ProcPwrPerf\=(.*)',a)
        ProcTurboMode=re.match('#?ProcTurboMode\=(.*)',a)
        if SysProfile: 
            results.append(SysProfile.groups()[0].strip())
        if ProcPwrPerf: 
            results.append(ProcPwrPerf.groups()[0].strip())
        if ProcTurboMode: 
            results.append(ProcTurboMode.groups()[0].strip())
    if len(results) > 1:
        raidstr = ','.join(results)
        return raidstr

###Check temp config
###温度
def getTempInfo(ip,lines):
    #只返回 温度
    results = []
    results.append(ip)
    for a in  lines:
        SystemBoardIn=re.match('System Board Inlet Temp(.*)',a)
        SystemBoardOut=re.match('System Board Exhaust Temp(.*)',a)
        if SystemBoardIn:
            #results.append(SystemBoardIn.groups()[0].strip())
            temp1=SystemBoardIn.groups()[0].strip().split()[1].replace('C','')
            results.append(temp1)
        if SystemBoardOut:
            temp2=SystemBoardOut.groups()[0].strip().split()[1].replace('C','')
            results.append(temp2)
    if len(results) > 1:
        raidstr = ','.join(results)
        return raidstr

#getbiosJobView
#getbiosJobView
def getbiosupdates(ip,lines):
    ##用于处理确定bios升级状态。进入待重启状态。
    #results1 = []
    results = []
    results.append('%s' % ip) 
    for a in  lines:
        jobname=re.match('Job Name\=(.*)',a)
        jobstatus=re.match('Status\=(.*)',a)
        jobtime=re.match('Start Time\=(.*)',a)
        jobinfo=re.match('Message\=(.*)',a)
        if jobname: 
            results.append(jobname.groups()[0].strip())
        if jobstatus: 
            results.append(jobstatus.groups()[0].strip())
        if jobtime: 
            results.append(jobtime.groups()[0].strip())
        if jobinfo: 
            infors = jobinfo.groups()[0].strip()
            if 'scheduled' in infors:
                results.append('scheduled')
            elif 'completed' in infors:
                results.append('completed')
            else:
                results.append(infors)
            results.append('|')

    if len(results) > 1:
        raidstr = ','.join(results)
        results1 = []
        newdstr = raidstr.strip('|').strip(',').split('|')
        for ni in range(len(newdstr)):
            if 'BIOS' in newdstr[ni]:
                tmps = newdstr[ni].strip(',')
                return tmps
            else:
                newdstr.append(newdstr[ni])
        if len(results1) > 1:
            tmpstr = ','.join(results1)
            return tmpstr

def operatemacs(ip,lines):
    ##专门处理mac地址和stg的函数，方便再次组合调用.
    for a in  lines:
        #匹配支持630和430
        #print a
        bmc=re.match('Current IP Address      =.*',a)
        #print "bmc is",bmc
        br3=re.match(r'NIC.Integrated.1-4-1.*|NIC.Embedded.4-1-1.*',a)
        #print "br3 is",br3
        br2=re.match(r'NIC.Integrated.1-3-1.*|NIC.Embedded.3-1-1.*',a)
        #print "br2 is",br2
        br1=re.match('NIC.Integrated.1-2-1.*|NIC.Embedded.2-1-1.*',a)
        #print "br1 is",br1
        br0=re.match(r'NIC.Integrated.1-1-1.*|NIC.Embedded.1-1-1.*',a)
        #print "br0 is",br0
        st1=re.match('Service Tag.*',a)
        model=re.match('System Model.*\=\s(.*)',a)
        biosversion=re.match('System BIOS Version.*\=\s(.*)',a)
        dracversion=re.match('Firmware Version.*\=\s(.*)',a)

        #print "st is",st1
        if br0:
            b0=re.search('..:..:..:..:..:..',br0.group()).group()
        if br1:
            b1=re.search('..:..:..:..:..:..',br1.group()).group()
        if br2:
            b2=re.search('..:..:..:..:..:..',br2.group()).group()
        if br3:
            b3=re.search('..:..:..:..:..:..',br3.group()).group()
        if st1:
            st=re.search('[0-9A-Z]{7}',st1.group()).group()
        if model:
            mode=model.groups()[0].strip()
        if biosversion:
            biosv=biosversion.groups()[0].strip()
        if dracversion:
            dracv=dracversion.groups()[0].strip()
    try:
        if st:
            nstrs = '%s,%s,%s,%s,%s' % (ip,mode,st,biosv,dracv)
            if b0:
                strs = '%s,%s,%s,%s,%s,%s|%s|%s|%s' % (ip,mode,st,biosv,dracv,b0,b1,b2,b3)
                print strs
                return strs
            else:
                strs = ip + ",WRONG," + "NOTDATA"
                print strs
                return strs
    except UnboundLocalError:
        strs = ip + ",WRONG," + "OTHERSERROR"
        if st:
            print nstrs
            return nstrs
        else:
            return strs
    except:
        strs = ip + ",WRONG," + "OTHERSERROR"
        if st:
            print nstrs
            return nstrs
        else:
            return strs
    
def operateraid(ip,lines):    
    #收集硬盘信息的函数
    results = []
    results.append('%s,' % ip)
    for std in lines:
        size=re.match('\s+Size.*\=\s(.*)',std)
        disk=re.match('Disk.Bay.(\d+):.*',std)

        Pro=re.match('\s+Manufacturer.*\=\s(.*)',std)
        serialnum=re.match('\s+SerialNumber\s+=\s(.*)',std)

        if size:
    	    sizes = size.groups()[0].strip()
            results.append(sizes)
        if disk:
            results.append(disk.groups()[0].strip())
        if Pro:
            results.append(Pro.groups()[0].strip())
        if serialnum:
            results.append(serialnum.groups()[0].strip())
    
    if len(results) > 1:
        raidstr = '|'.join(results)
        #print raidstr
        return raidstr
    else:
        results.append('NODISKDATA')
        raidstr = '|'.join(results)
        return raidstr

def operateraidstatus(ip,lines):    
    #收集硬盘log信息的函数
    results = []
    results.append('%s,' % ip)
    for std in lines:
        size=re.match('\s+Size.*\=\s(.*)',std)
        disk=re.match('Disk.Bay.(\d+):.*',std)
        status=re.match('\s+Status\s+\=\s(.*)',std)
        Pro=re.match('\s+Manufacturer.*\=\s(.*)',std)
        serialnum=re.match('\s+SerialNumber\s+=\s(.*)',std)
        mediatype=re.match('\s+MediaType\s+=\s(.*)',std)

        if size:
    	    sizes = size.groups()[0].strip()
            results.append(sizes)
        if disk:
            results.append(disk.groups()[0].strip())
        if status:
            results.append(status.groups()[0].strip())
        if Pro:
            results.append(Pro.groups()[0].strip())
        if mediatype:
            results.append(mediatype.groups()[0].strip())
        if serialnum:
            results.append(serialnum.groups()[0].strip())
            results.append(',')
    
    if len(results) > 1:
        raidstr = '|'.join(results)
        results1 = []
        results1.append('%s' % ip)
        newdstr = raidstr.strip(',').strip('|').split(',')
        disknu = len(newdstr) - 1
        results1.append('DiskNU:%s' % disknu)
        if ( 'Warning' in raidstr ) or 'Unknown' in raidstr or 'Failed' in raidstr:
            for sei in range(len(newdstr)):
                #print newdstr[sei]
                tempstrs = str(newdstr[sei].strip('|'))
                if 'Warning' in tempstrs or 'Unknown' in tempstrs or 'Failed' in tempstrs:
                    results1.append('%s' % tempstrs)

        else:
            results1.append('RAIDLOG:OK')
                    
        if len(results1) > 1: 
                #results1.append('OK')
                raidstr1 = ','.join(results1)
#                print  raidstr1
                return raidstr1
    else:
        results.append('NODISKDATA')
        raidstr = '|'.join(results)
        return raidstr
        
        
def operatesel(ip,lines):    
    #处理sel log的函数
    results = []
    results.append('%s' % ip)
    for std in lines:
        sdate = re.match('Date/Time:\s+(.*)',std)
        severity = re.match('Severity:\s+(.*)',std)
        problem = re.match('Description:\s(.*)',std)
    
        if severity:
            serity= severity.groups()[0].strip()
            results.append(serity)
        if sdate:
            results.append(sdate.groups()[0].strip())
        if problem: 
            results.append(problem.groups()[0].strip())
            results.append(',')
    
    if len(results) > 1:
        raidstr = '|'.join(results)
#        print raidstr
        results1 = []
        results1.append('%s' % ip)
        newdstr = raidstr.strip(',').strip('|').split(',')
        num = 0
        if 'Critical' in raidstr:
            for sei in range(len(newdstr)):
                if 'Critical' in newdstr[sei]:
                    if 'Non-Critical' in newdstr[sei]:
                        pass
                    else:
                        if num < 2:
#                            print newdstr[sei]
                            results1.append(newdstr[sei].strip('|'))
                            num += 1
                        else:
                            break
        else:
           # print 'ok'
            results1.append('IDRACLOG:OK')
                    
        if len(results1) > 1: 
                #results1.append('OK')
                raidstr1 = ','.join(results1)
#                print  raidstr1
                return raidstr1
    else:
        results.append('NOINFO')
        raidstr = ','.join(results)
        return raidstr


def ssh_cmd(user, passwd, ip, port, cmd):
    newlist = []
    #此列表是为了装多个不通命令组合设计的， 因为之前关于有数据收集的时候都是每次运行一次，然后单独处理 返回。 那么这次是将一堆命令都放
    #进来 然后处理后 一次性返回。
    #print len(cmd)
    for cmdi in range(len(cmd)):
#        print cmdi
        cmdm = cmd[cmdi]
        print ip + "\t" +  cmdm
        ssh = pexpect.spawn('ssh -p%s %s@%s "%s"' % (port, user, ip, cmdm))
        try:
           i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=20)
           if i == 0 :
              ssh.sendline(passwd)
           elif i == 1:
              ssh.sendline('yes\n')
              ssh.expect('password: ')
              ssh.sendline(passwd)
              ssh.sendline(cmdi)
        except pexpect.EOF:
            if key == 'getmacs' or  key == 'raid' or key == 'getsel' :
                strs = ip + ",WRONG," + "EOF"
                print strs
                return strs
            ssh.close()
        except pexpect.TIMEOUT:
            if key == 'getmacs' or  key == 'raid' or key == 'getsel' :
                strs = ip + ",WRONG," + "TIMEOUT"
                print strs
                return strs
            ssh.close()
        except:
            if key == 'getmacs' or  key == 'raid' or key == 'getsel' :
                strs = ip + ",WRONG," + "NONE_PASSWORDWONG"
                print strs
                return strs
            ssh.close()
        else:
            if key == 'getmacs':
                lines=ssh.readlines()
                return operatemacs(ip,lines)
            elif key == 'raid':
                lines=ssh.readlines()
                return operateraid(ip,lines)

            elif key == 'getsel':
                lines=ssh.readlines()
                return operatesel(ip,lines)
            #elif key == 'getcpu':
            #    lines=ssh.readlines()
            #    return getCpuInfo(ip,lines)

#def getTempInfo(ip,lines):
            ###20180420 操作Temp配置
            elif key == 'getTemp':
                lines=ssh.readlines()
                if cmdi == 0:
                    stgtmp = operatestg(ip,lines).split(',')
                    if len(stgtmp) > 2:
                        newlist.extend(stgtmp)
                        ssh.close()
                        continue
                if cmdi == 1:
                    #return getCpuInfo(ip,lines)
                    raidtmp=getTempInfo(ip,lines).split(',')
                    #raidtmp=getCpuInfo(ip,lines)
                    if len(raidtmp) > 1:
                        #newlist.append('%s' % raidtmp[1])
                        newlist.extend(raidtmp[1:])
                        ssh.close()
                        continue

            ###20180420 操作cpu配置
            elif key == 'getcpu':
                lines=ssh.readlines()
                if cmdi == 0:
                    stgtmp = operatestg(ip,lines).split(',')
                    if len(stgtmp) > 2:
                        newlist.extend(stgtmp)
                        ssh.close()
                        continue
                if cmdi == 1:
                    #return getCpuInfo(ip,lines)
                    raidtmp=getCpuInfo(ip,lines).split(',')
                    #raidtmp=getCpuInfo(ip,lines)
                    if len(raidtmp) > 1:
                        #newlist.append('%s' % raidtmp[1])
                        newlist.extend(raidtmp[1:])
                        ssh.close()
                        continue

            ##因为之前getbiosJobView 输出结果没有stg和机型，所以调整以下
            elif key == 'getbiosJobView':
                lines=ssh.readlines()
                if cmdi < 1:
                    stgtmp = operatestg(ip,lines).split(',')
                    if len(stgtmp) > 2:
                        newlist.extend(stgtmp)
                        ssh.close()
                        continue
                if cmdi < 2:
                    raidtmp = getbiosupdates(ip,lines).split(',')
                    if len(raidtmp) > 1:
                        #newlist.append('%s' % raidtmp[1])
                        newlist.extend(raidtmp[1:])
                        ssh.close()
                        continue

            elif key == 'allreport':
                lines=ssh.readlines()
                if cmdi < 1:
                    stgtmp = operatestg(ip,lines).split(',')
                    if len(stgtmp) > 2:
                        newlist.extend(stgtmp)
                        ssh.close()
                        continue

                if cmdi < 2:
                    #operateraidstatus
                    raidtmp = operateraidstatus(ip,lines).split(',')
            #        print raidtmp
                    if len(raidtmp) > 1:
                        #newlist.append('%s' % raidtmp[1])
                        #newlist.extend(raidtmp[1:])
                        ##将raid信息部分不再以,分割，而是以;分割，方便之后进行固定提取 raid日志、idrac日志
                        newraidinfo = ';'.join(raidtmp[1:])
                        newlist.append('%s' % newraidinfo)
                        ssh.close()
                        continue
                if cmdi < 3:
                    raidtmp = operatesel(ip,lines).split(',')
            #        print raidtmp
                    if len(raidtmp) > 1:
                        newraidinfo = ';'.join(raidtmp[1:])
#                        newlist.extend(newraidinfo)
                        #newlist.append('%s' % raidtmp[1])
                        newlist.append('%s' % newraidinfo)
                        ssh.close()
                        continue
            else:
                for a in ssh.readlines():
                    jieguo = re.match('.*successful',a)
                    if jieguo:
                        print  ip + "\t" + cmdm + "\tok"
        ssh.close()
#    print newlist
    if len(newlist) > 2:
        tmpstr = raidstr = ','.join(newlist)
#        print tmpstr
        return tmpstr

def getnfsip(ip,nfsservers):
    """ 
    通过ip地址获取所在机房的nfsserver的ip地址
    此函数也仅用于在固件升级的时候去使用
    """
    ip1 = ip
    #ipss是 所有nfsserver的ip信息列表，下面会先算他的网段，然后在让进来的ip地址取匹配他属于哪个nfsserver
    #假如匹配不上那就回复一个默认nfsserver地址，可能不一定好用
    ipss = nfsservers.split()
    skd = ''
    for i in range(len(ipss)):
        nfs=ipss[i].split('/')[0]
        IPD=IPy.IP('%s' % ipss[i] , make_net=True)
        if ip1 in IPy.IP('%s' % IPD):
        #    print ip1 + ' is in ' + nfs
            sdk = nfs
            return nfs 
          #  break
    if skd == '':
       #假如没有找打那就返回默认的nfsserver的ip地址，不一定能用
       return nfsserver



def main(keys):
	
    """
    1. 此函数为执行ssh并发调用的主函数
    macs 为一个字典用于存放ssh并发执行时候返回的结果，目前只在ssh调用中对getmacs命令信息进行返回
    其他的命令 为执行ssh命令 无需返回值
    2. key 为命令，因为命令在下面cmds字典进行了具体条数定义
    """


    global macs,key
    global fileName,binPath,basePath,confPath,writelog,alldracip,rundracip,sshport,sshuser,sshpassword,newpasswd,nfsserver

    ###获取绝对路径
    fileName = os.path.abspath(__file__)
    binPath = os.path.dirname(os.path.realpath(__file__))
    basePath = os.path.dirname(binPath)
    confPath = basePath + '/config/'

    ###读取idrac密码等信息，以及ip地址存放的位置
    conf = ConfigParser.ConfigParser()
    #if os.path.isfile(local_file):
    #return True
    conf.read("%s/config.ini" % confPath)

    FilesPath = conf.get('globle','filepath')
    if not os.path.isdir(FilesPath):
        os.mkdir(FilesPath)
    writelog   = FilesPath + conf.get("globle", "writeniclog")
    reportlog   = FilesPath + conf.get("globle", "reportlog")
    raidlog    = FilesPath + conf.get("globle", "raidlog")

    alldracip  = confPath + conf.get("globle", "alldracip")
    rundracip  = confPath + conf.get("globle", "runracip")
    process    = int(conf.get("globle", "processes"))
    newpasswd  = conf.get("globle", "newpasswd")
    ntpserver  = conf.get("globle", "ntpserver")
    timezone   = conf.get("globle", "timezone")
    
    nfsserver = conf.get("globle", "nfsserver")
    nfsservers = conf.get("globle", "nfsservers")
    pathurl    = conf.get("globle", "pathurl")
    biospkgs = conf.get("globle", "biospkgs")
    idracpkgs = conf.get("globle", "idracpkgs")


    sshport    = conf.get("globle", "port")
    sshuser    = conf.get("dell", "user")
    sshpassword = conf.get("dell", "password")
    

    macs = {}
    if keys == 'get_all_macs':
        key = 'getmacs'
        writeniclog =  writelog
        filedracip =  alldracip
    elif keys == 'raid':
        key = 'raid'
        filedracip = alldracip
        writeniclog = raidlog
    elif keys == 'power_all_off':
        key = 'poweroff'
        filedracip =  alldracip
    else:
        key = keys
        filedracip = rundracip
        writeniclog = writelog
        
    user = sshuser
    password = sshpassword
    port = sshport

    cmds = {
    'getmacs':[
    'racadm getsysinfo'
    ],
    'getcpu':[
    'racadm getsysinfo',
    'racadm get BIOS.SysProfileSettings.',
    ],
    'clear':[
    'racadm jobqueue delete --all',
    ],
    'reset':[
    'racadm racreset',
    ],
    'pxe':[
    'racadm jobqueue delete --all',
    'racadm config -g cfgServerInfo -o cfgServerFirstBootDevice pxe',
    'racadm config -g cfgServerInfo -o cfgServerBootOnce 1',
    'racadm serveraction powercycle',
    ],
    'reboot':[
    'racadm serveraction powercycle'
    ],
    'poweroff':[
    'racadm serveraction powerdown'
    ],
    'poweron':[
    'racadm serveraction powerup'
    ],
    'getTemp':[
    'racadm getsysinfo',
    'racadm getsensorinfo'
    ],
    'biosturbo':[
    'racadm jobqueue delete --all',
    'racadm set bios.procsettings.controlledturbo Enabled',
    'racadm jobqueue create BIOS.Setup.1-1',
    'racadm serveraction powercycle'
    ],  
    'biosdiscpu':[
    'racadm jobqueue delete --all',
    'racadm set BIOS.ProcSettings.LogicalProc Disabled',
    'racadm jobqueue create BIOS.Setup.1-1',
    'racadm serveraction powercycle'
    ],  
    'bios':[
    'racadm jobqueue delete --all',
    'racadm set BIOS.MiscSettings.ErrPrompt Disabled',
    'racadm set BIOS.SysProfileSettings.SysProfile PerfOptimized ',
    'racadm set BIOS.BiosBootSettings.BootSeq HardDisk.List.1-1,NIC.Integrated.1-1-1'
    'racadm jobqueue create BIOS.Setup.1-1',
    'racadm set NIC.nicconfig.1.LegacyBootProto PXE',
    'racadm set NIC.nicconfig.3.LegacyBootProto NONE',
    'racadm jobqueue create NIC.Integrated.1-1-1',
    'racadm jobqueue create NIC.Integrated.1-3-1',
    'racadm serveraction powercycle',
    'racadm set iDRAC.IPMILan.1.Enable Enabled',
    'racadm set BIOS.MiscSettings.ErrPrompt Disabled'
    ],
    'zulong':[
    'racadm jobqueue delete --all',
    'racadm set NIC.nicconfig.3.LegacyBootProto pxE',
    'racadm jobqueue create NIC.Integrated.1-3-1'
    ],
    'allreport':[
    'racadm getsysinfo',
    'racadm raid get pdisks -o',
    'racadm getsel'
    ],
    'raid':[
    'racadm raid get pdisks -o'
    ],
    ## 修改idrac密码
    'changepasswd':[
    'racadm config -g cfgUserAdmin -o cfgUserAdminPassword -i 2 %s' % newpasswd
    ],
#    getsel
    'getsel':[
    'racadm getsel'
    ],
    'getbiosJobView':[
    'racadm getsysinfo',
    'racadm jobqueue view'
    ],
#    getsel
    'clearlog':[
    'racadm clrsel'
    ],
    ## 设置ntp server
    'setntp':[
    'racadm set idrac.NTPConfigGroup.NTP1 %s' % ntpserver ,
    'racadm set idrac.NTPConfigGroup.NTPEnable Enabled',
    'racadm set idrac.time.Timezone %s' % timezone
    ],
    'ipmi':[
    'racadm set iDRAC.IPMILan.1.Enable Enabled',
    'racadm set idrac.time.Timezone %s' % timezone
    ]
    }

    pool = Pool(processes=process)
    dracips = []
    result = []

    with open(filedracip,'r') as f:
        for ii in f.readlines():
            abc = ii.split()
            dracips.append(abc[0])

    for i in range(len(dracips)):
        ip = dracips[i]
        if key == 'idracUpdate' or key == 'biosUpdate':
            ##对于升级固件，用各地管理机的nfsserver 提供支持,
            ##由下面一行去根据每一个ip地址去算装机的nfsserverip。
            nfsip = getnfsip(ip,nfsservers)
            cmds = {
                'biosUpdate':[
                'racadm jobqueue delete --all',
                #'racadm update -f %s -e %s -a TRUE -t HTTP' % (biospkgs, pathurl), 
                'racadm update -f %s -l %s:%s ' % (biospkgs, nfsip, pathurl)
                #'racadm serveraction powercycle'
                ],
                ##升级idrac
                'idracUpdate':[
                'racadm jobqueue delete --all',
                #'racadm update -f %s -e %s -a TRUE -t HTTP' % (idracpkgs, pathurl), 
                #'racadm update -f %s -l %s:%s ' % (idracpkgs, nfsserver, pathurl), 
                'racadm update -f %s -l %s:%s ' % (idracpkgs, nfsip, pathurl), 
                #'racadm serveraction powercycle'
                ]
                }
        try:
            get_ssh_result = pool.apply_async(ssh_cmd,(user, password, ip, port, cmds[key],))
        except w:
            print w,ip
        else:
            result.append(get_ssh_result)

    pool.close()
    pool.join()

    files = []
    if key == 'getmacs' or key == 'raid' or key == 'getsel' or key == 'allreport' or key == 'getbiosJobView' or key == 'getcpu' or key == 'getTemp':
    #if key == 'getmacs' or key == 'raid' or key == 'getsel' or key == 'allreport':
        for res in result:
            #print "res is"
            #print res
            try:
                if key == 'idracUpdate' or key == 'biosUpdate':
                    i2 = res.get(timeout=120,)
                else:
                    i2 = res.get(timeout=60,)
            except:
                i2 = "something wrong"
    #            print i2
            else:
                #i2 = str(i2)
                #if not re.search(r'wrong|None',i2,re.I):
                files.append(i2)


    #if key == 'getmacs' or key == 'raid':
    if key == 'getmacs' or key == 'raid' or key == 'getsel' or key == 'allreport' or key == 'getbiosJobView' or key == 'getcpu' or key == 'getTemp':
    #if key == 'getmacs' or key == 'raid' or key == 'getsel' or key == 'allreport' or key == 'getbiosJobView' or key == 'getcpu' :
    #if key == 'getmacs' or key == 'raid' or key == 'getsel' or key == 'allreport' or key == 'getbiosJobView':
    #if key == 'getmacs' or key == 'raid' or key == 'getsel':
        with open(writeniclog,'w') as ff:
            for filel in range(len(files)):
                if files[filel]:
                    ff.write("%s\n" % (files[filel]))

    if key == 'allreport':
    #收集报警信息的时候，把正常的剔除掉
    #if key == 'getmacs' or key == 'raid' or key == 'getsel':
        with open(reportlog,'w') as ff:
            for filel in range(len(files)):
                if files[filel]:
                        if ('RAIDLOG:OK' in files[filel] or 'NODISKDATA' in  files[filel] ) and 'IDRACLOG:OK' in files[filel]:
                            pass
                        else:
                            ff.write("%s\n" % (files[filel]))


if __name__ == '__main__':
    #global key
    ###默认传入获取服务器信息的
#    keys = 'get_all_macs'
    #keys = 'allreport'
    #keys = 'clear'
    keys = 'getTemp'
    #keys = 'getbiosJobView'
    #keys = 'reset'
    #keys = 'biosUpdate'
    #keys = 'idracUpdate'
    #keys = 'getsel'
    #keys = 'raid'
    main(keys)
    #main(keys1)
