#!/usr/bin/python
#encoding=utf-8
# -*-coding:utf-8 -*-

import os, sys, string
import MySQLdb
import xml.dom.minidom
import xml.etree.ElementTree as ET
import time, datetime

from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from xml.etree.ElementTree import dump
from xml.etree.ElementTree import Comment
from xml.etree.ElementTree import tostring

reload(sys)
sys.setdefaultencoding('utf-8')

filename="CAS-check-result.xml"
CAS =ElementTree()
purOrder =Element("CASCheck")
CAS._setroot(purOrder)

print "H3C CAS-Checking Start."

def getTime():
    time.localtime(time.time())
    currentTime = ''
    currentTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    return currentTime

def exeSql(sql):
    cursor.execute(sql)
    return cursor.fetchone()

def indent(elem,level=0):
    i ="\n"+level*"    "
    #print elem;
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "    "
        for e in elem:
            #print e
            indent(e,level+1)
        if not e.tail or not e.tail.strip():
            e.tail =i
    if level and (not elem.tail or not elem.tail.strip()):
        elem.tail =i
    return elem

#CVM主机的版本信息,全局有效
versionCVM = ''
versionCVMBig = ''
versionCVMSmall = ''

##################################查询CAS版本是否满足巡检要求,开始##################################
lines = 0
cmdTmp = 'find /etc/ -name h3c_cas_cvk-version'
textlist = os.popen(cmdTmp).readlines()
lines = len(textlist)

if (lines > 0):
    cmd = 'cat /etc/h3c_cas_cvk-version'

else:
    cmdTmp = 'find /etc/ -name cas_cvk-version'
    textlist = os.popen(cmdTmp).readlines()
    lines = 0
    lines = len(textlist)

    if(lines > 0):
        cmd = 'cat /etc/cas_cvk-version'
    else:
        #XML内容编写
        checkName = '查询巡检工具访问的主机是否为CVM主机'.decode('utf-8')
        suggest = '确保巡检工具访问的主机为CVM主机'.decode('utf-8')
        itemXML = Element("CVM",{'name':checkName, 'suggest':suggest})

        result = '异常'.encode('utf-8')
        desc = '巡检工具访问的主机是不CVM主机'.encode('utf-8')
        SubElement(itemXML, 'host', {'result':result, 'desc':desc})

        #生成XML内容
        purOrder.append(itemXML)
        indent(purOrder)
        CAS.write(filename,"utf-8",True)

        print "H3C CAS-Checking failed for the host is not CVM."
        #退出巡检
        exit()

#XML文件中的检查项目,以及建议说明
checkName = '查询CAS版本是否满足巡检要求'.encode('utf-8')
suggest = '确保CAS3.0版本满足巡检要求,要求版本至少为E0301'.encode('utf-8')
itemXML = Element("versionCAS",{'name':checkName, 'suggest':suggest})

textlist = os.popen(cmd).readlines()
tmpText = textlist[0]

#查询CVM主机的版本信息:
findIdex = tmpText.find('.')
if findIdex > -1:
    #获取CAS大版本信息
    versionCVMBig = tmpText[findIdex-1:findIdex+2]

    #获取小版本信息
    tmpVersionSmall = tmpText[findIdex+3:]
    findIdex = tmpVersionSmall.find(' ')
    if findIdex > -1:
        versionCVMSmall = tmpVersionSmall[:findIdex]

    versionCVM = versionCVMBig + ' (' + versionCVMSmall + ')'

    if(float(versionCVMBig) >= 3.0):
        #XML内容编写
        versionCAS = versionCVM
        result = '正常'.encode('utf-8')
        desc = 'CAS版本满足巡检要求'.encode('utf-8')
        SubElement(itemXML, 'version', {'versionCAS':versionCAS, 'result':result, 'desc':desc})

        #生成XML内容
        purOrder.append(itemXML)
    else:
        #XML内容编写
        versionCAS = versionCVM
        result = '异常'.encode('utf-8')
        desc = 'CAS版本无法满足巡检要求'.encode('utf-8')
        SubElement(itemXML, 'version', {'versionCAS':versionCAS, 'result':result, 'desc':desc})

        #生成XML内容
        purOrder.append(itemXML)
        indent(purOrder)
        CAS.write(filename,"utf-8",True)

        print "H3C CAS-Checking failed for the CAS version is wrong."
        #退出巡检
        exit()

else:
    #XML内容编写
    versionCAS = ''
    result = '异常'.encode('utf-8')
    desc = '无法查询到CAS版本信息'.encode('utf-8')
    SubElement(itemXML, 'version', {'versionCAS':versionCAS, 'result':result, 'desc':desc})

    #生成XML内容
    purOrder.append(itemXML)
    indent(purOrder)
    CAS.write(filename,"utf-8",True)

    print "H3C CAS-Checking failed for the host has no CAS version file."
    #退出巡检
    exit()

##################################查询CAS版本是否满足巡检要求,结束##################################

##################################检查是否为CVM主机,开始##################################
#XML文件中的检查项目,以及建议说明
checkName = '查询巡检工具访问的主机是否为CVM主机'.decode('utf-8')
suggest = '确保巡检工具访问的主机为CVM主机'.decode('utf-8')
itemXML = Element("CVM",{'name':checkName, 'suggest':suggest})

#0:表示Tomcat服务未运行;1:表示Tomcat服务正常运行
isTomcat = 0
#0:表示主机未部署CVM软件包cas.war;1:表示主机部署了CVM软件包cas.war
isCVM = 0
#当主机安装了CVM软件包,并且Tomcat服务正常运行,则表示该主机为CVM主机
isCVMHost = 0

###########查询主机是否部署了CVM的软件包cas.war,开始###########
if (float(versionCVMBig) < 3.0):
    cmd = 'find /var/lib/tomcat6/webapps -name cas.war'
else:
    #CAS3.0升级到了tomcat8服务
    cmd = 'find /var/lib/tomcat8/webapps -name cas.war'

#执行查询命令
textlist = os.popen(cmd).readlines()

lines = len(textlist)

if (lines > 0):
    #分析查询结果
    tmpText = textlist[0]
    findIdex = tmpText.find('cas.war')
    if findIdex > -1:
        isCVM = 1 #部署了CVM软件包cas.war
    else:
        isCVM = 0 #未部署CVM软件包cas.war
else:
    isCVM = 0 #未部署CVM软件包cas.war
###########查询主机是否部署了CVM的软件包cas.war,结束###########

###########查询Tomcat服务是否正常运行,开始###########
if (float(versionCVMBig) < 3.0):
    cmd = 'service tomcat6 status'
else:
    #CAS3.0升级到了tomcat8服务
    cmd = 'service tomcat8 status'

#执行查询命令
textlist = os.popen(cmd).readlines()

lines = len(textlist)
if (lines > 0):
    #分析查询结果
    tmpText = textlist[0]
    findIdex = tmpText.find('is running')
    if findIdex > -1:
        isTomcat = 1 #Tomcat服务正常运行
    else:
        isTomcat = 0 #Tomcat服务未运行
else:
    isTomcat = 0 #Tomcat服务未运行
###########查询Tomcat服务是否正常运行,结束###########

#如果是CVM主机,则继续巡检,否则退出巡检工作
if (isCVM == 1 and isTomcat == 1):
    isCVMHost = 1
else:
    isCVMHost = 0

if (isCVMHost == 1):
    #XML内容编写
    result = '正常'.encode('utf-8')
    desc = '巡检工具访问的主机是CVM主机'.encode('utf-8')
    SubElement(itemXML, 'host', {'result':result, 'desc':desc})

    #生成XML内容
    purOrder.append(itemXML)
else:
    #XML内容编写
    result = '异常'.encode('utf-8')
    desc = '巡检工具访问的主机是不CVM主机,请检查配置是否正确'.encode('utf-8')
    SubElement(itemXML, 'host', {'result':result, 'desc':desc})

    #生成XML内容
    purOrder.append(itemXML)
    indent(purOrder)
    CAS.write(filename,"utf-8",True)

    print "H3C CAS-Checking failed for the host is not CVM or not Master CVM."
    #退出巡检
    exit()
##################################检查是否为CVM主机,结束##################################

try:
    conn = MySQLdb.connect(host="localhost",user="root",passwd="1q2w3e",db="vservice",charset="utf8")
except Exception, e:
    print e
    sys.exit()

cursor =conn.cursor()

##################################查询CAS版本是否满足巡检要求,结束##################################

checkNum = 1
##################################集群高可靠性配置,开始##################################
print "num=%s, %s: Check Cluster's HA conf. Starting" % (checkNum, getTime())
#XML文件中的检查项目,以及建议说明
checkName = '检查集群高可靠性(HA)功能'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = '建议开启集群高可靠性(HA)功能'.encode('utf-8')
itemXML = Element("clusterHA",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select cluster.NAME from TBL_CLUSTER cluster where cluster.ENABLE_HA  = 0"

#查询数据库
cursor.execute(sql)



index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #XML内容编写
    clusterName = row[0]
    state = '未开启'.encode('utf-8')
    SubElement(itemXML, 'Cluster', {'index':str(index), 'clusterName':clusterName, 'state':state})
    
    index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check Cluster's HA conf. Successful" % (checkNum, getTime())
checkNum += 1
##################################集群高可靠性配置,结束##################################

##################################计算资源DRS配置,开始##################################
print "num=%s, %s: Check Cluster's Computer DRS conf. Starting" % (checkNum, getTime())
#XML文件中的检查项目,以及建议说明
checkName = '检查集群计算资源DRS功能'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = '建议开启集群计算资源DRS功能'.encode('utf-8')
itemXML = Element("clusterDRS",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select cluster.NAME from TBL_CLUSTER cluster where cluster.ENABLE_LB = 0"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #XML内容编写
    clusterName = row[0]
    state = '未开启'.encode('utf-8')
    SubElement(itemXML, 'Cluster', {'index':str(index), 'clusterName':clusterName, 'state':state})

    index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check Cluster's Computer DRS conf. Successful" % (checkNum, getTime())
checkNum += 1
##################################计算资源DRS配置,结束##################################

##################################查询CVK版本是否与CVM版本一致,开始##################################
print "num=%s, %s: Check 'the version of CVK host is equal with CVM host'. Starting" % (checkNum, getTime())
#XML文件中的检查项目,以及建议说明
checkName = '检查CVK主机和CVM主机的CAS版本是否一致'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = 'CVK主机和CVM主机的CAS版本必须保持一致'.encode('utf-8')
itemXML = Element("version",{'name':checkName, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.CVK_VERSION from TBL_HOST host"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #判断CVK的版本是否于CVM一致
    if row[1] != versionCVM:
        #XML内容编写
        hostName = row[0]
        versionCVK = row[1]
        SubElement(itemXML, 'Host', {'index':str(index), 'hostName':hostName, 'versionCVK':versionCVK, 'versionCVM':versionCVM})

        index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'the version of CVK host is equal with CVM host'. Successful" % (checkNum, getTime())
checkNum += 1
##################################查询CVK版本是否与CVM版本一致,结束##################################

##################################主机状态,开始##################################
print "num=%s, %s: Check 'the host status'. Starting" % (checkNum, getTime())
checkName = '检查主机状态是否正常'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = '确保所有主机状态正常'.encode('utf-8')
itemXML = Element("hostState",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.STATUS, host.MAINTAIN from TBL_HOST host"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #主机处于“不正常”状态
    if row[1] == 0:
        #XML内容编写
        hostName = row[0]
        hostState = '不正常'.encode('utf-8')
        SubElement(itemXML, 'Host', {'index':str(index), 'hostName':hostName, 'state':hostState})

        index += 1
    #主机处于运行,但是进入了维护模式
    elif row[1] == 1:
        if row[2] == 1:
            #XML内容编写
            hostName = row[0]
            hostState = '维护模式'.encode('utf-8')
            SubElement(itemXML, 'Host', {'index':str(index), 'hostName':hostName, 'state':hostState})

            index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'the host status'. Successful" % (checkNum, getTime())
checkNum += 1
##################################主机状态,结束##################################

##################################NTP配置,开始##################################
print "num=%s, %s: Check 'the NTP config'. Starting" % (checkNum, getTime())
checkName = '检查NTP服务器配置'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = '建议配置主备NTP服务器'.encode('utf-8')
itemXML = Element("NTPServer",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select parameter.VALUE from TBL_PARAMETER parameter where parameter.NAME = 'ntp.server'"
#查询数据库
cursor.execute(sql)
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    MasterNTPServer = ''
    if row[0] == None:
        #XML内容编写
        ntpstate = '未配置'.encode('utf-8')
        SubElement(itemXML, 'masterNTPServer', {'state':ntpState})
    else:
        MasterNTPServer = str(row[0])

#定义数据库查询SQL语句
sql = "select parameter.VALUE from TBL_PARAMETER parameter where parameter.NAME = 'ntp.standbyserver'"
#查询数据库
cursor.execute(sql)
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    StandbyNTPServer = ''

    if row[0] == None:
        #XML内容编写
        ntpState = '未配置'.encode('utf-8')
        SubElement(itemXML, 'stangbyNTPServer', {'state':ntpState})
    else:
        StandbyNTPServer = str(row[0])

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'the NTP config'. Successful" % (checkNum, getTime())
checkNum += 1
##################################NTP配置:,结束##################################

##################################主机时间差异对比,开始##################################
print "num=%s, %s: Check 'the system time diff between CVM host and CVK host'. Starting" % (checkNum, getTime())
checkName = '检查CVK和CVM主机的时间差'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = 'CVK和CVM主机的系统时间需要保持一致'.encode('utf-8')
itemXML = Element("hostTime",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR from TBL_HOST host where host.STATUS = 1"

#查询数据库
cursor.execute(sql)

numRows = int(cursor.rowcount)
hostNames = [''] * numRows
dateCVK = [''] * numRows

dateCVM = datetime.datetime.now()

dateCVMformat = dateCVM.strftime('%Y-%m-%d %H:%M:%S')

timeCVM = time.mktime(dateCVM.timetuple())

Num = 0
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    hostNames[Num] = row[0]

    #通过date命令查询主机下的系统时间
    cmd = "ssh %s 'date -R'" % (row[1])
    textlist = os.popen(cmd).readlines()
    tmpDate = str(textlist[0])
    dateCVK[Num] = tmpDate[:-1]

    Num += 1

index = 1
Num = 0
while Num < numRows:
    dateTmp = datetime.datetime.strptime(dateCVK[Num], '%a, %d %b %Y %H:%M:%S +0800')

    timeCVK = time.mktime(dateTmp.timetuple())

    if timeCVM >= timeCVK:
        diffTime = timeCVM - timeCVK
    else:
        diffTime = timeCVK - timeCVM

    if diffTime >= 60:
        #XML内容编写
        hostName = hostNames[Num]
        SubElement(itemXML, 'SysTime', {'index':str(index), 'hostName':hostName, 'timeCVK':str(dateTmp), 'timeCVM':str(dateCVMformat)})
        index += 1

    Num += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'the system time diff between CVM host and CVK host'. Successful" % (checkNum, getTime())
checkNum += 1
##################################主机时间差异对比,结束##################################

##################################主机系统时间和物理时间差异对比,开始##################################
print "num=%s, %s: Check 'the time diff between System and Hardware'. Starting" % (checkNum, getTime())
checkName = '检查主机系统时间和物理时钟的时间差'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = '主机系统时间和物理时钟需要保持一致'.encode('utf-8')
itemXML = Element("hostHWTime",{'name':checkName, 'level':level, 'suggest':suggest})

#获取CVM主机名称
cmd = 'hostname'
textlist = os.popen(cmd).readlines()
hostNameTemp = textlist[0]
hostNameCVM = hostNameTemp[:-1]

#查询CVM主机是否被加入到主机池
sql = "select host.NAME, host.IPADDR from TBL_HOST host where host.NAME = '%s'" % (hostNameCVM)
cursor.execute(sql)
numRows = int(cursor.rowcount)

#如果CVM主机没有加入主机池,则查询CVM主机的系统时间和物理时钟
if (numRows == 0):
    #查询CVM主机的系统时间和物理时钟
    dateCVM_SYS = datetime.datetime.now()
    dateSystemFormat = dateCVM_SYS.strftime('%Y-%m-%d %H:%M:%S')
    timeCVM_SYS = time.mktime(dateCVM.timetuple())

    #查询物理时钟及处理
    cmd = "hwclock"
    textlist = os.popen(cmd).readlines()
    tmpTime_HW_CHAR = textlist[0]

    index = 1
    findIdex = tmpTime_HW_CHAR.find('CST')
    if findIdex > -1:
        time_HW_CHAR = tmpTime_HW_CHAR[:findIdex - 1]
        dateCVM_HW = datetime.datetime.strptime(time_HW_CHAR, '%a %d %b %Y %I:%M:%S %p')
        timeCVM_HW = time.mktime(dateCVM_HW.timetuple())
        if timeCVM_SYS >= timeCVM_HW:
            diffTime = timeCVM_SYS - timeCVM_HW
        else:
            diffTime = timeCVM_HW - timeCVM_SYS

        if diffTime >= 60:
            #XML内容编写
            SubElement(itemXML, 'HWTime', {'index':str(index), 'hostName':hostNameCVM, 'timeSystem':str(dateSystemFormat), 'timeHW':str(dateCVM_HW)})
            index += 1

#############################查询CVK主机的系统时间和物理时钟是否一致
#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR from TBL_HOST host where host.STATUS = 1"

#查询数据库
cursor.execute(sql)

while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #通过date命令查询主机下的系统时间
    cmd = "ssh %s 'date -R'" % (row[1])
    textlist = os.popen(cmd).readlines()
    tmpTime_SYS_CHAR = str(textlist[0])
    time_SYS_CHAR = tmpTime_SYS_CHAR[:-1]
    dateCVK_SYS = datetime.datetime.strptime(time_SYS_CHAR, '%a, %d %b %Y %H:%M:%S +0800')
    timeCVK_SYS = time.mktime(dateCVK_SYS.timetuple())

    #查询物理时钟及处理
    cmd = "hwclock"
    textlist = os.popen(cmd).readlines()
    tmpTime_HW_CHAR = textlist[0]
    findIdex = tmpTime_HW_CHAR.find('CST')
    if findIdex > -1:
        time_HW_CHAR = tmpTime_HW_CHAR[:findIdex - 1]
        dateCVK_HW = datetime.datetime.strptime(time_HW_CHAR, '%a %d %b %Y %I:%M:%S %p')
        timeCVK_HW = time.mktime(dateCVK_HW.timetuple())

    if timeCVK_SYS >= timeCVK_HW:
        diffTime = timeCVK_SYS - timeCVK_HW
    else:
        diffTime = timeCVK_HW - timeCVK_SYS

    if diffTime >= 60:
        #XML内容编写
        hostName = row[0]
        SubElement(itemXML, 'HWTime', {'index':str(index), 'hostName':hostName, 'timeSystem':str(dateCVK_SYS), 'timeHW':str(dateCVK_HW)})
        index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'the time diff between System and Hardware'. Successful" % (checkNum, getTime())
checkNum += 1
##################################主机系统时间和物理时间差异对比,结束##################################

##################################主机CPU利用率信息,开始##################################
print "num=%s, %s: Check 'CPU use of the host'. Starting" % (checkNum, getTime())
checkName = '检查主机CPU利用率'.encode('utf-8')
level = '紧急'.encode('utf-8')
suggest = '建议主机CPU利用率不要超过80%'.encode('utf-8')
itemXML = Element("useHostCPU",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, hostDetail.CPU_RATE, max(hostDetail.TIME) from TBL_HOST_CPU_MEM_DETAIL hostDetail, TBL_HOST host where hostDetail.HOST_ID =  host.ID and host.STATUS = 1 group by hostDetail.HOST_ID"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #如果主机的CPU利用率超过阈值,则显示
    if (row[1] >= 80):
        #XML内容编写
        hostName = row[0]
        useCPU = str(row[1]) + '%'
        SubElement(itemXML, 'CPU', {'index':str(index), 'hostName':hostName, 'useCPU':useCPU})
        index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'CPU use of the host'. Successful" % (checkNum, getTime())
checkNum += 1
##################################主机CPU利用率信息,结束##################################

##################################主机MEM利用率信息,开始##################################
print "num=%s, %s: Check 'Memory use of the host'. Starting" % (checkNum, getTime())
checkName = '检查主机内存利用率'.encode('utf-8')
level = '紧急'.encode('utf-8')
suggest = '建议主机内存利用率不要超过80%'.encode('utf-8')
itemXML = Element("useHostMem",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, hostDetail.MEMORY_RATE, max(hostDetail.TIME) from TBL_HOST_CPU_MEM_DETAIL hostDetail, TBL_HOST host where hostDetail.HOST_ID =  host.ID and host.STATUS = 1 group by hostDetail.HOST_ID"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #如果主机的内存利用率超过阈值,则显示
    if (row[1] >= 80):
        #XML内容编写
        hostName = row[0]
        useCPU = str(row[1]) + '%'
        SubElement(itemXML, 'Memory', {'index':str(index), 'hostName':hostName, 'useMem':useCPU})
        index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'Memory use of the host'. Successful" % (checkNum, getTime())
checkNum += 1
##################################主机MEM利用率信息,结束##################################

##################################主机分区利用率信息,开始##################################
print "num=%s, %s: Check 'Partition use of the host'. Starting" % (checkNum, getTime())
checkName = '检查主机分区利用率'.encode('utf-8')
level = '紧急'.encode('utf-8')
suggest = '建议主机分区利用率不要超过80%'.encode('utf-8')
itemXML = Element("useHostPartition",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.ID from TBL_HOST host where host.STATUS = 1"

#查询数据库
cursor.execute(sql)

numRows = int(cursor.rowcount)
hostName = [''] * numRows
hostID = [''] * numRows

Num = 0
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    hostName[Num] = row[0]
    hostID[Num] = row[1]

    Num += 1

index = 1
Num = 0
while Num < numRows:
    #定义数据库查询SQL语句
    sql = "select host.NAME, p.PARTITION_NAME, p.PARTITION_TYPE, p.MOUNTED_DIR, max(p.LAST_UPDATE_TIME), p.SIZE, p.USED from TBL_HOST_PARTITION_DETAIL p, TBL_HOST host where host.ID = p.HOST_ID and p.HOST_ID = %s and p.LAST_UPDATE_TIME >= (select max(p.LAST_UPDATE_TIME) from TBL_HOST_PARTITION_DETAIL p where p.HOST_ID = %s) group by p.HOST_ID, p.MOUNTED_DIR" % (hostID[Num], hostID[Num])

    #查询数据库
    cursor.execute(sql)

    while (True):
        row = cursor.fetchone()
        if row == None:
            break

        #如果主机下的分区利用率超过阈值,则显示
        if ((row[6]/row[5])*100 >= 80):
            #XML内容编写
            hostName = row[0]
            deviceName = row[1]
            fileSystemType = row[2]
            mountPoint = row[3]
            usePartition = "%.2f" % (float(row[6])/float(row[5]) * 100)
            SubElement(itemXML, 'Partition', {'index':str(index), 'hostName':hostName, 'deviceName':deviceName, 'fileSystemType':fileSystemType, 'mountPoint':mountPoint, 'usePartition':str(usePartition)+'%'})
            index += 1

    Num += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'Partition use of the host'. Successful" % (checkNum, getTime())
checkNum += 1
##################################主机分区利用率信息,结束##################################

##################################虚拟交换机状态,开始##################################
print "num=%s, %s: Check 'vSwitch status'. Starting" % (checkNum, getTime())
checkName = '检查虚拟交换机状态'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = '确保虚拟交换机状态正常'.encode('utf-8')
itemXML = Element("vSwitchState",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR, vswitch.NAME from TBL_VSWITCH vswitch, TBL_HOST host where vswitch.HOST_ID = host.ID and host.STATUS = 1 order by host.ID"

#查询数据库
cursor.execute(sql)

index = 1
Num = 0
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #查询虚拟交换机状态
    cmd = "ssh %s 'ip link | grep %s'" % (row[1], row[2])
    textlist = os.popen(cmd).readlines()
    tmpSwitch = str(textlist[0])

    findIdex = tmpSwitch.find('UP')
    if (findIdex == -1):
        #XML内容编写
        hostName = row[0]
        vSwitchName = row[2]
        vSwitchState = '不活动'.encode('utf-8')
        SubElement(itemXML, 'vSwitch', {'index':str(index), 'hostName':hostName, 'vSwitchName':vSwitchName, 'vSwitchState':vSwitchState})
        index += 1

    Num += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'vSwitch status'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟交换机状态,结束##################################

##################################主机下只有一个管理虚拟交换机,开始##################################
print "num=%s, %s: Check 'the host has a manager vswitch'. Starting" % (checkNum, getTime())
checkName = '检查主机是否只有管理虚拟交换机'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = '管理、存储和业务虚拟交换机不能合并使用'.encode('utf-8')
itemXML = Element("vSwitchState",{'name':checkName, 'level':level, 'suggest':suggest})

#查询主机名称
sql = "select host.ID, host.NAME from TBL_HOST host order by host.ID"
#查询数据库
cursor.execute(sql)

numHostRows = int(cursor.rowcount)
hostID = [''] * numHostRows
hostName = [''] * numHostRows
ii = 0
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    hostID[ii] = row[0]
    hostName[ii] = row[1]

    ii += 1

#查询主机下的虚拟交换机名称
index = 1
numHost = 0
while numHost < numHostRows:
    #查询虚拟交换机名称
    sql = "select vswitch.NAME from TBL_VSWITCH vswitch where vswitch.HOST_ID = %s order by vswitch.NAME" % (hostID[numHost])
    #查询数据库
    cursor.execute(sql)

    numVSwitch = int(cursor.rowcount)
    if numVSwitch == 1:
        row = cursor.fetchone()
        #XML内容编写
        hostName = hostName[numHost]
        vSwitchName = row[0]
        num = 1
        SubElement(itemXML, 'vSwitch', {'index':str(index), 'hostName':hostName, 'vSwitchNums':'1', 'vSwitchName':vSwitchName})
        index += 1

    numHost += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'the host has a manager vswitch'. Successful" % (checkNum, getTime())
checkNum += 1
##################################主机下只有一个管理虚拟交换机,结束##################################

##################################虚拟交换机的网卡状态,开始##################################
print "num=%s, %s: Check 'Eth status of the vSwitch'. Starting" % (checkNum, getTime())
checkName = '检查虚拟交换机的网卡状态'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = '确保虚拟交换机绑定的物理网卡状态正常'.encode('utf-8')
itemXML = Element("vSwitchEth",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR, host.STATUS, vswitch.NAME, vswitch_pnic.PNIC from TBL_VSWITCH vswitch, TBL_VSWITCH_PNIC vswitch_pnic, TBL_HOST host where vswitch.HOST_ID = host.ID and vswitch.ID = vswitch_pnic.VSWITCH_ID"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #如果主机未正常运行,则继续查询下一台主机
    if (row[2] != 1):
        continue

    eths = row[4]
    #判断虚拟交换机是否做都网卡绑定
    findIdex = eths.find('eth')
    if findIdex == -1:
        continue

    for eth in eths.split(','):
        cmd = "ssh %s 'ethtool %s'" % (row[1], eth)
        textEth = os.popen(cmd).readlines()
        lines = len(textEth)

        #查询状态异常的网卡
        findIdex = textEth[lines-1].find('Link detected: no')
        if findIdex > -1:
            #XML内容编写
            hostName = row[0]
            vSwitchName = row[3]
            ethName = eth
            ethState = '不活动'.encode('utf-8')
            SubElement(itemXML, 'Eth', {'index':str(index), 'hostName':hostName, 'vswitchName':vSwitchName, 'ethName':ethName, 'ethState':ethState})
            index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'Eth status of the vSwitch'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟交换机的网卡状态,结束##################################

##################################虚拟交换机链路冗余配置,开始##################################
print "num=%s, %s: Check 'Eth bond of the vSwitch'. Starting" % (checkNum, getTime())
checkName = '检查虚拟交换机的链路冗余状态'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = '建议虚拟交换机绑定多个物理网卡,提高链路冗余性'.encode('utf-8')
itemXML = Element("vSwitchEthBond",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, vswitch.NAME, vswitch_pnic.PNIC from TBL_VSWITCH vswitch, TBL_VSWITCH_PNIC vswitch_pnic, TBL_HOST host where vswitch.HOST_ID = host.ID and vswitch.ID = vswitch_pnic.VSWITCH_ID order by host.NAME, vswitch.NAME"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    eths = row[2]
    #判断虚拟交换机是否做都网卡绑定
    findIdex = eths.find('eth')
    if findIdex > -1:
        findIdex = eths.find(',')
        if findIdex == -1:
            #XML内容编写
            hostName = row[0]
            vSwitchName = row[1]
            ethName = row[2]
            SubElement(itemXML, 'vSwitch', {'index':str(index), 'hostName':hostName, 'vSwitchName':vSwitchName, 'ethName':ethName})
            index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'Eth bond of the vSwitch'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟交换机链路冗余配置,结束##################################

##################################集群下CVK主机的虚拟交换机名称是否一致,开始##################################
print "num=%s, %s: Check 'the host's vSwitch name of cluster is equal'. Starting" % (checkNum, getTime())
checkName = '检查集群下CVK主机的虚拟交换机名称是否一致'.encode('utf-8')
level = '紧急'.encode('utf-8')
suggest = '确保集群下CVK主机的虚拟交换机名称保持一致'.encode('utf-8')
itemXML = Element("vSwitchDiff",{'name':checkName, 'level':level, 'suggest':suggest})

#查询集群名
sql = "select cluster.ID, cluster.NAME from TBL_CLUSTER cluster"
#查询数据库
cursor.execute(sql)
numClusterRows = int(cursor.rowcount)
clusterName = [''] * numClusterRows
clusterID = [''] * numClusterRows

#查询集群ID和集群名称
Num = 0
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    clusterID[Num] = row[0]
    clusterName[Num] = row[1]

    Num += 1

#查询各个集群下CVK主机的虚拟交换机名称
index = 1
numCluster = 0
while numCluster < numClusterRows:
    #查询集群下的主机名称
    sql = "select host.ID, host.NAME from TBL_HOST host where host.CLUSTER_ID = %s order by host.ID" % (clusterID[numCluster])
    #查询数据库
    cursor.execute(sql)

    numHostRows = int(cursor.rowcount)
    hostID = [''] * numHostRows
    hostName = [''] * numHostRows
    ii = 0
    while (True):
        row = cursor.fetchone()
        if row == None:
            break

        hostID[ii] = row[0]
        hostName[ii] = row[1]

        ii += 1

    #查询主机下的虚拟交换机名称
    numHost = 0
    vswitchName = [''] * numHostRows
    while numHost < numHostRows:
        #查询虚拟交换机名称
        sql = "select vswitch.NAME from TBL_VSWITCH vswitch where vswitch.HOST_ID = %s order by vswitch.NAME" % (hostID[numHost])
        #查询数据库
        cursor.execute(sql)

        i = 0
        while (True):
            row = cursor.fetchone()
            if row == None:
                break

            if i == 0:
                vswitchName[numHost] = row[0]
                i = 1
            else:
                vswitchName[numHost] = vswitchName[numHost] + ',' + row[0]

        #print '  ', clusterName[numCluster], hostName[numHost], vswitchName[numHost]

        numHost += 1

    #比较主机间的虚拟交换机名称是否一致
    i = 0
    while i < numHostRows:
        j = i + 1
        while j < numHostRows:
            if vswitchName[j] != vswitchName[i]:
                #print '  ', clusterName[numCluster], hostName[i], vswitchName[i]
                #print '  ', clusterName[numCluster], hostName[j], vswitchName[j]
                #XML内容编写
                clusterNameTmp = clusterName[numCluster]
                hostName01 =  hostName[i]
                vswitchName01 =  vswitchName[i]
                hostName02 =  hostName[j]
                vswitchName02 =  vswitchName[j]
                groupXML = SubElement(itemXML, 'Group', {'index':str(index), 'clusterName':clusterNameTmp, 'hostName01':hostName01, 'hostName02':hostName02})

                SubElement(groupXML, "vSwitch",{'hostName':hostName01, 'vswitchName':vswitchName01})
                SubElement(groupXML, "vSwitch",{'hostName':hostName02, 'vswitchName':vswitchName02})
                index += 1


            j += 1

        i += 1

    numCluster += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'the host's vSwitch name of cluster is equal'. Successful" % (checkNum, getTime())
checkNum += 1
##################################集群下CVK主机的虚拟交换机名称是否一致,结束##################################

##################################主机的存储池状态,开始##################################
print "num=%s, %s: Check 'StoragePool status'. Starting" % (checkNum, getTime())
checkName = '检查存储池状态'.encode('utf-8')
level = '紧急'.encode('utf-8')
suggest = '确保存储池状态正常'.encode('utf-8')
itemXML = Element("StoragePoolState",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR, host.HOST_USER, host.PW, host.STATUS from TBL_HOST host where host.STATUS = 1"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #通过'virsh pool-list'命令查询主机下的所有存储池的名称和状态信息
    cmd = "ssh %s 'virsh pool-list --all'" % (row[1])
    textlist = os.popen(cmd).readlines()
    lines = len(textlist)

    line = 2
    poolName = ' '
    while line < lines - 1:
        #查询存储池状态是否为“不活动”
        findIdex = textlist[line].find('inactive')
        if findIdex > -1:
            #查询存储池名称
            findIdex = textlist[line].find(' ')
            if findIdex > -1:
                tmpPoolName = textlist[line]
                poolName = tmpPoolName[:findIdex]

                #XML内容编写
                hostName =  row[0]
                storagePoolName =  poolName
                storagePoolState =  '不活动'.encode('utf-8')
                SubElement(itemXML, 'StoragePool', {'index':str(index), 'hostName':hostName, 'storagePoolName':storagePoolName, 'storagePoolState':storagePoolState})
                index += 1
        else:
            line += 1
            continue

        line += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'StoragePool status'. Successful" % (checkNum, getTime())
checkNum += 1
##################################主机的存储池状态,结束##################################

##################################主机的存储池利用率,开始##################################
print "num=%s, %s: Check 'StoragePool use'. Starting" % (checkNum, getTime())
checkName = '检查存储池利用率'.encode('utf-8')
level = '紧急'.encode('utf-8')
suggest = '确保存储池利用率不超过80%'.encode('utf-8')
itemXML = Element("StoragePoolUse",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR, host.HOST_USER, host.PW, host.STATUS from TBL_HOST host where host.STATUS = 1"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #通过'virsh pool-list'命令查询主机下的所有存储池的名称和状态信息
    cmd = "ssh %s 'virsh pool-list --all'" % (row[1])
    textlist = os.popen(cmd).readlines()
    lines = len(textlist)

    line = 2
    poolState = 0
    poolName = ' '
    while line < lines - 1:
        #查询存储池状态是否为“不活动”
        findIdex = textlist[line].find('inactive')
        if findIdex > -1:
                line += 1
                continue
        else:
            #查询存储池状态是否为“活动”
            findIdex = textlist[line].find('active')
            if findIdex > -1:
                poolState = 1
            else:
                line += 1
                continue

        #查询存储池名称
        findIdex = textlist[line].find(' ')
        if findIdex > -1:
            tmpPoolName = textlist[line]
            poolName = tmpPoolName[:findIdex]
        else:
            line += 1
            continue

        #print "poolName=%s, PoolState=%s" % (poolName)

        #通过'virsh pool-list'命令查询主机下的所有存储池的名称和状态信息
        cmd = "ssh %s 'virsh pool-dumpxml %s'" % (row[0], poolName)
        textPools = os.popen(cmd).readlines()
        poolLines = len(textPools)
        poolLine = 0
        textPool = ''
        while poolLine < poolLines:
            textPool += textPools[poolLine]
            poolLine += 1

        root = ET.fromstring(textPool)
        type = root.get('type')

        #查询存储池总容量
        for child in root.findall('capacity'):
            capacity = int(child.text)

        #查询存储池已分配容量
        for child in root.findall('allocation'):
            allocation = int(child.text)

        #查询存储池路径
        for elem in root.iterfind('target/path'):
            path = elem.text

        if (capacity == 0):
            storagePoolUsed = 0
        else:
            storagePoolUsed = "%.2f" % (float(allocation)/float(capacity) * 100)

        if (float(storagePoolUsed) >= 80):
            #XML内容编写
            hostName =  row[0]
            storagePoolName =  poolName
            storagePoolPath = path
            useStoragePool = str(storagePoolUsed) + '%'
            SubElement(itemXML, 'StoragePool', {'index':str(index), 'hostName':hostName, 'storagePoolName':storagePoolName, 'path':storagePoolPath, 'useStoragePool':useStoragePool})
            index += 1

        line += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'StoragePool use'. Successful" % (checkNum, getTime())
checkNum += 1
##################################主机的存储池利用率,结束##################################

##################################主机共享文件系统挂载信息,开始##################################
print "num=%s, %s: Check 'Sharefile mount'. Starting" % (checkNum, getTime())
checkName = '检查共享文件系统挂载'.encode('utf-8')
level = '一般'.encode('utf-8')
suggest = '建议一个共享文件系统仅被一个集群下的主机挂载'.encode('utf-8')
itemXML = Element("SharefileMount",{'name':checkName, 'level':level, 'suggest':suggest})


#定义数据库查询SQL语句
sql = "select sharefile.NAME, sharefile.ID from TBL_SHARE_FILE_SYSTEM sharefile"

#查询数据库
cursor.execute(sql)

numRows = int(cursor.rowcount)

shareFileNames = [''] * numRows
shareFileID = [''] * numRows

Num = 0
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    shareFileNames[Num] = row[0]
    shareFileID[Num] = row[1]

    Num += 1

#定义数据库查询SQL语句

index = 1
Num = 0
while Num < numRows:
    sql = "select cluster.NAME from TBL_STORAGE_POOL_CONFIG config, TBL_HOST host, TBL_CLUSTER cluster where config.HOST_ID = host.ID and host.CLUSTER_ID = cluster.ID and config.SHARE_FILE_SYSTEM_ID = %s group by cluster.NAME" % (shareFileID[Num])

    #查询数据库
    cursor.execute(sql)

    numClusters = int(cursor.rowcount)

    if numClusters > 1:
        #XML内容编写
        shareFileName =  shareFileNames[Num]
        sharefileXML = SubElement(itemXML, 'Sharefile', {'index':str(index), 'sharefileName':shareFileName})

        while (True):
            row = cursor.fetchone()
            if row == None:
                break

            #print '  ', shareFileNames[Num], row[0]
            #XML内容编写
            clusterName =  row[0]
            SubElement(sharefileXML, 'Cluster', {'clusterName':clusterName})

        index += 1

    Num += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'Sharefile mount'. Successful" % (checkNum, getTime())
checkNum += 1
##################################主机共享文件系统挂载信息,结束##################################

##################################集群下未挂载共享文件系统的主机信息,开始##################################
print "num=%s, %s: Check 'Sharefile mount of Cluster'host'. Starting" % (checkNum, getTime())
checkName = '检查集群下主机挂载共享文件系统信息'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = '确保共享文件系统被集群下的所有主机挂载'.encode('utf-8')
itemXML = Element("clusterMount",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select sharefile.NAME, sharefile.ID from TBL_SHARE_FILE_SYSTEM sharefile"

#查询数据库
cursor.execute(sql)

numRows = int(cursor.rowcount)

shareFileNames = [''] * numRows
shareFileID = [''] * numRows

Num = 0
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    shareFileNames[Num] = row[0]
    shareFileID[Num] = row[1]

    Num += 1

#定义数据库查询SQL语句

index = 1
Num = 0
while Num < numRows:
    sql = "select cluster.NAME, cluster.ID from TBL_STORAGE_POOL_CONFIG config, TBL_HOST host, TBL_CLUSTER cluster where config.HOST_ID = host.ID and host.CLUSTER_ID = cluster.ID and config.SHARE_FILE_SYSTEM_ID = %s group by cluster.NAME" % (shareFileID[Num])

    #查询数据库
    cursor.execute(sql)

    numClusters = int(cursor.rowcount)
    clusterNames = [''] * numClusters
    clusterIDs = [''] * numClusters

    ii = 0
    while (True):
        row = cursor.fetchone()
        if row == None:
            break

        clusterNames[ii] = row[0]
        clusterIDs[ii] = row[1]
        #print shareFileNames[Num], row[0]
        ii += 1

    ii = 0
    while ii < numClusters:
        sql = "select host.NAME from TBL_HOST host where host.CLUSTER_ID = %s and host.ID not in (select host.ID from TBL_STORAGE_POOL_CONFIG config, TBL_HOST host, TBL_CLUSTER cluster where config.HOST_ID = host.ID and host.CLUSTER_ID = cluster.ID and config.SHARE_FILE_SYSTEM_ID = %s and cluster.ID = %s)" % (clusterIDs[ii], shareFileID[Num], clusterIDs[ii])
        #查询数据库
        cursor.execute(sql)

        #用来判断是否输出共享文件系统和集群信息
        hostDetect = 0

        while (True):
            row = cursor.fetchone()
            if row == None:
                break

            if (hostDetect == 0):
                #XML内容编写
                shareFileName = shareFileNames[Num]
                clusterName = clusterNames[ii]
                sharefileXML = SubElement(itemXML, 'Sharefile', {'index':str(index), 'sharefileName':shareFileName, 'clusterName':clusterName})
                hostDetect = 1
                index += 1

            #XML内容编写
            hostName = row[0]
            SubElement(sharefileXML, 'Host', {'hostName':hostName})

        ii += 1

    Num += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'Sharefile mount of Cluster'host'. Successful" % (checkNum, getTime())
checkNum += 1
##################################集群下未挂载共享文件系统的主机信息,结束##################################

##################################虚拟机配置文件,开始##################################
print "num=%s, %s: Check 'VM config'. Starting" % (checkNum, getTime())
#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR, host.HOST_USER, host.PW, vm.DOMAIN_NAME, vm.AUTO_MIGRATE, vm.HA_MANAGE, vm.AUTO_BOOTING from TBL_HOST host, TBL_DOMAIN vm where vm.HOST_ID = host.ID and host.STATUS = 1 order by host.NAME"

#查询数据库
cursor.execute(sql)

numVMS = int(cursor.rowcount)
vmNames = [''] * numVMS
hostNames = [''] * numVMS
cpuModes = [''] * numVMS
vmHAs = [''] * numVMS
vmBlueHAs = [''] * numVMS
vmAutoMigrates = [0] * numVMS
vmTimeSyncs = [0] * numVMS
vmAutoBootings = [0] * numVMS

Num = 0
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    hostNames[Num] = row[0]
    vmNames[Num] = row[4]
    vmAutoMigrates[Num] = row[5]
    vmHAs[Num] = row[6]
    vmAutoBootings[Num] = row[7]

    #通过'virsh dumpxml'命令虚拟机配置文件信息
    cmd = "ssh %s 'virsh dumpxml %s'" % (row[1], row[4])
    textVMs = os.popen(cmd).readlines()
    VMXMLLines = len(textVMs)

    VMXMLLine = 0
    textVMXML = ''
    while VMXMLLine < VMXMLLines:
        textVMXML += textVMs[VMXMLLine]
        VMXMLLine += 1

    #print textVMXML

    root = ET.fromstring(textVMXML)
    #查询时间同步
    for child in root.findall('timesync'):
        vmTimeSyncs[Num] = int(child.text)

    #查询蓝屏HA
    for child in root.findall('osha'):
        vmBlueHAs[Num] = int(child.text)


    #查询CPU工作模式
    for child in root.findall('cpu'):
        cpuModes[Num] = child.get('mode')

    Num += 1

    #print '  ', hostNames[Num], vmNames[Num], vmAutoMigrates[Num], vmHAs[Num], vmTimeSyncs[Num], vmBlueHAs[Num], cpuModes[Num]

#XML文件中的检查项目说明
checkName = '检查虚拟机的CPU模式配置'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "建议虚拟机的CPU模式使用'兼容模式',提升虚拟机迁移兼容性".encode('utf-8')
itemXML = Element("VMCPUMode",{'name':checkName, 'level':level, 'suggest':suggest})

index = 1
Num = 0
while Num < numVMS:
    if (cpuModes[Num] == 'host-model'):
        #print '  ', hostNames[Num], vmNames[Num], cpuModes[Num]
        #XML内容编写
        VMName =  vmNames[Num]
        hostName = hostNames[Num]
        cpuMode = '主机匹配模式'.encode('utf-8')
        SubElement(itemXML, 'VM', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'CPUMode':cpuMode})
        index += 1
    elif (cpuModes[Num] == 'host-passthrough'):
        #XML内容编写
        VMName =  vmNames[Num]
        hostName = hostNames[Num]
        cpuMode = '直通模式'.encode('utf-8')
        SubElement(itemXML, 'VM', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'CPUMode':cpuMode})
        index += 1
    Num += 1

#生成XML内容
purOrder.append(itemXML)

#XML文件中的检查项目说明
checkName = '检查虚拟机的自动迁移功能配置'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "建议虚拟机开启自动迁移功能,否则在触发DRS功能时虚拟机无法迁移".encode('utf-8')
itemXML = Element("VMAutoMirgate",{'name':checkName, 'level':level, 'suggest':suggest})

index = 1
Num = 0
while Num < numVMS:
    if (vmAutoMigrates[Num] == 0):
        #print '  ', hostNames[Num], vmNames[Num], vmAutoMigrates[Num]
        #XML内容编写
        VMName =  vmNames[Num]
        hostName = hostNames[Num]
        AutoMigrate = '关闭'.encode('utf-8')
        SubElement(itemXML, 'VM', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'AutoMigrate':AutoMigrate})
        index += 1
    Num += 1

#生成XML内容
purOrder.append(itemXML)
checkNum += 1

#XML文件中的检查项目说明
checkName = '检查虚拟机的HA(高可靠性)功能配置'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "建议开启虚拟机的HA(高可靠性)功能配置,否则在触发HA功能时虚拟机无法迁移到其他正常CVK主机".encode('utf-8')
itemXML = Element("VMHA",{'name':checkName, 'level':level, 'suggest':suggest})

index = 1
Num = 0
while Num < numVMS:
    if (vmHAs[Num] == 0):
        #print '  ', hostNames[Num], vmNames[Num], vmHAs[Num]
        #XML内容编写
        VMName =  vmNames[Num]
        hostName = hostNames[Num]
        HA = '关闭'.encode('utf-8')
        SubElement(itemXML, 'VM', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'HA':HA})
        index += 1
    Num += 1

#生成XML内容
purOrder.append(itemXML)

#XML文件中的检查项目说明
checkName = '检查虚拟机的时钟同步功能配置'.encode('utf-8')
level = '一般'.encode('utf-8')
suggest = "建议开启虚拟机的时钟同步功能,使虚拟机和CVK的时钟保持一致".encode('utf-8')
itemXML = Element("VMtimeSyncs",{'name':checkName, 'level':level, 'suggest':suggest})

index = 1
Num = 0
while Num < numVMS:
    if (vmTimeSyncs[Num] == 0):
        #print '  ', hostNames[Num], vmNames[Num], vmTimeSyncs[Num]
        #XML内容编写
        VMName =  vmNames[Num]
        hostName = hostNames[Num]
        timeSyncs = '关闭'.encode('utf-8')
        SubElement(itemXML, 'VM', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'timeSyncs':timeSyncs})
        index += 1
    Num += 1

#生成XML内容
purOrder.append(itemXML)

#XML文件中的检查项目说明
checkName = '检查虚拟机的蓝屏HA功能配置'.encode('utf-8')
level = '一般'.encode('utf-8')
suggest = "建议开启虚拟机的蓝屏HA功能".encode('utf-8')
itemXML = Element("VMBlueHA",{'name':checkName, 'level':level, 'suggest':suggest})

index = 1
Num = 0
while Num < numVMS:
    if (vmBlueHAs[Num] == 0):
        #print '  ', hostNames[Num], vmNames[Num], vmBlueHAs[Num]
        #XML内容编写
        VMName =  vmNames[Num]
        hostName = hostNames[Num]
        blueHA = '关闭'.encode('utf-8')
        SubElement(itemXML, 'VM', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'blueHA':blueHA})
        index += 1
    Num += 1

#生成XML内容
purOrder.append(itemXML)

#XML文件中的检查项目说明
checkName = '检查虚拟机的自动启动功能配置'.encode('utf-8')
level = '一般'.encode('utf-8')
suggest = "建议开启虚拟机的自动启动功能".encode('utf-8')
itemXML = Element("VMAutoBooting",{'name':checkName, 'level':level, 'suggest':suggest})

index = 1
Num = 0
while Num < numVMS:
    if (vmAutoBootings[Num] == 0):
        #print '  ', hostNames[Num], vmNames[Num], vmAutoBootings[Num]
        #XML内容编写
        VMName =  vmNames[Num]
        hostName = hostNames[Num]
        autoBooting = '关闭'.encode('utf-8')
        SubElement(itemXML, 'VM', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'autoBooting':autoBooting})
        index += 1
    Num += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM config'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机配置文件,结束##################################

##################################虚拟机网卡,开始##################################
print "num=%s, %s: Check 'VM eth'. Starting" % (checkNum, getTime())
#XML文件中的检查项目说明
checkName = '检查虚拟机的网卡类型'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "建议虚拟机使用'高速网卡(virtio)'".encode('utf-8')
itemXML = Element("ethType",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR, host.HOST_USER, host.PW, vm.DOMAIN_NAME from TBL_HOST host, TBL_DOMAIN vm where vm.HOST_ID = host.ID and host.STATUS = 1 order by host.NAME"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #通过'virsh dumpxml'命令虚拟机配置文件信息
    cmd = "ssh %s 'virsh dumpxml %s'" % (row[1], row[4])
    textVMs = os.popen(cmd).readlines()
    VMXMLLines = len(textVMs)

    VMXMLLine = 0
    textVMXML = ''
    while VMXMLLine < VMXMLLines:
        textVMXML += textVMs[VMXMLLine]
        VMXMLLine += 1

    #print textVMXML

    macAddress = ''
    vwitchName = ''
    netType = ''
    root = ET.fromstring(textVMXML)
    #查询设备型号
    for elem in root.iterfind('devices/interface'):
        fileType = elem.get('type')
        if(fileType == 'bridge'):
            for child in elem.findall('mac'):
                macAddress = child.get('address')

            for child in elem.findall('source'):
                vwitchName = child.get('bridge')

            for child in elem.findall('model'):
                netType = child.get('type')

            if (netType != 'virtio'):
                #print '  ', row[0], row[4], macAddress, vwitchName, netType
                VMName = row[4]
                hostName = row[0]
                if (netType == 'rtl8139'):
                    ethType = '普通网卡'.encode('utf-8')
                elif (netType == 'e1000'):
                    ethType = 'Intel e1000网卡'.encode('utf-8')
                #XML内容编写
                SubElement(itemXML, 'eth', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'vwitchName':vwitchName, 'macAddress':macAddress, 'ethType':ethType})
                index += 1
        else:
            continue

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM eth'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机网卡,结束##################################

##################################虚拟机网卡加速,开始##################################
print "num=%s, %s: Check 'VM eth speed'. Starting" % (checkNum, getTime())
#XML文件中的检查项目说明
checkName = '检查虚拟机网卡的内核加速功能'.encode('utf-8')
level = '一般'.encode('utf-8')
suggest = "建议开启虚拟机网卡的内核加速功能".encode('utf-8')
itemXML = Element("ethSpeedAdd",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR, host.HOST_USER, host.PW, vm.DOMAIN_NAME from TBL_HOST host, TBL_DOMAIN vm where vm.HOST_ID = host.ID and host.STATUS = 1 order by host.NAME"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #通过'virsh dumpxml'命令虚拟机配置文件信息
    cmd = "ssh %s 'virsh dumpxml %s'" % (row[1], row[4])
    textVMs = os.popen(cmd).readlines()
    VMXMLLines = len(textVMs)

    VMXMLLine = 0
    textVMXML = ''
    while VMXMLLine < VMXMLLines:
        textVMXML += textVMs[VMXMLLine]
        VMXMLLine += 1

    #print textVMXML

    macAddress = ''
    vwitchName = ''
    netType = ''
    vhost = ''
    root = ET.fromstring(textVMXML)
    #查询设备型号
    for elem in root.iterfind('devices/interface'):
        fileType = elem.get('type')
        if(fileType == 'bridge'):
            for child in elem.findall('mac'):
                macAddress = child.get('address')

            for child in elem.findall('source'):
                vwitchName = child.get('bridge')

            for child in elem.findall('driver'):
                vhost = child.get('name')

            for child in elem.findall('model'):
                netType = child.get('type')

            if ((netType == 'virtio') and (vhost != 'vhost')):
                #print '  ', row[0], row[4], macAddress, vwitchName, vhost
                #XML内容编写
                VMName = row[4]
                hostName = row[0]
                speed = '未开启'.encode('utf-8')
                SubElement(itemXML, 'eth', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'vwitchName':vwitchName, 'macAddress':macAddress, 'vhost':speed})
                index += 1
        else:
            continue

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM eth speed'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机网卡加速,结束##################################

##################################虚拟机磁盘缓存,开始##################################
print "num=%s, %s: Check 'VM disk buffer'. Starting" % (checkNum, getTime())
#XML文件中的检查项目说明
checkName = '检查虚拟机磁盘的缓存模式配置'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "建议虚拟机磁盘的缓存模式为'直接读写',以提升数据的安全性".encode('utf-8')
itemXML = Element("diskCacheMode",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR, host.HOST_USER, host.PW, vm.DOMAIN_NAME from TBL_HOST host, TBL_DOMAIN vm where vm.HOST_ID = host.ID and host.STATUS = 1 order by host.NAME"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #通过'virsh dumpxml'命令虚拟机配置文件信息
    cmd = "ssh %s 'virsh dumpxml %s'" % (row[1], row[4])
    textVMs = os.popen(cmd).readlines()
    VMXMLLines = len(textVMs)

    VMXMLLine = 0
    textVMXML = ''
    while VMXMLLine < VMXMLLines:
        textVMXML += textVMs[VMXMLLine]
        VMXMLLine += 1

    #print textVMXML

    root = ET.fromstring(textVMXML)
    #查询磁盘缓存
    for elem in root.iterfind('devices/disk'):
        fileType = elem.get('type')
        device = elem.get('device')
        if((fileType == 'file') and (device == 'disk')):
            for child in elem.findall('source'):
                filePath = child.get('file')

            for child in elem.findall('driver'):
                diskCache = child.get('cache')
                if (diskCache != 'directsync'):
                    #print '  ', row[0], row[4], filePath, diskCache
                    #XML内容编写
                    VMName = row[4]
                    hostName = row[0]
                    if (diskCache == 'writeback'):
                        cacheMode = '二级虚拟缓存(writeback)'.encode('utf-8')
                    elif (diskCache == 'writethrough'):
                        cacheMode = '一级物理缓存(writethrough)'.encode('utf-8')
                    elif (diskCache == 'none'):
                        cacheMode = '一级虚拟缓存(none)'.encode('utf-8')
                    SubElement(itemXML, 'disk', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'diskPath':filePath, 'diskCacheMode':cacheMode})
                    index += 1
        else:
            continue

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM disk buffer'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机磁盘缓存,结束##################################

##################################虚拟机磁盘总线,开始##################################
print "num=%s, %s: Check 'VM disk bus'. Starting" % (checkNum, getTime())
#XML文件中的检查项目说明
checkName = '检查虚拟机磁盘的总线类型配置'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "建议虚拟机磁盘的总线类型为'高速磁盘',以提升虚拟机磁盘的性能".encode('utf-8')
itemXML = Element("diskBusType",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR, host.HOST_USER, host.PW, vm.DOMAIN_NAME, vm.AUTO_MIGRATE, vm.HA_MANAGE from TBL_HOST host, TBL_DOMAIN vm where vm.HOST_ID = host.ID and host.STATUS = 1 order by host.NAME"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #通过'virsh dumpxml'命令虚拟机配置文件信息
    cmd = "ssh %s 'virsh dumpxml %s'" % (row[1], row[4])
    textVMs = os.popen(cmd).readlines()
    VMXMLLines = len(textVMs)

    VMXMLLine = 0
    textVMXML = ''
    while VMXMLLine < VMXMLLines:
        textVMXML += textVMs[VMXMLLine]
        VMXMLLine += 1

    #print textVMXML

    root = ET.fromstring(textVMXML)
    #查询磁盘总线
    for elem in root.iterfind('devices/disk'):
        fileType = elem.get('type')
        device = elem.get('device')
        if((fileType == 'file') and (device == 'disk')):
            for child in elem.findall('source'):
                filePath = child.get('file')

            for child in elem.findall('target'):
                diskBus = child.get('bus')

            for child in elem.findall('address'):
                controllerID = child.get('controller')

            if diskBus == 'scsi':
                for controller in root.iterfind('devices/controller'):
                    if (controller.get('type') == diskBus) and (controller.get('index') == controllerID):
                        model = controller.get('model')

            if (diskBus != 'virtio'):
                if (diskBus == 'scsi') and (model != 'virtio-scsi'):
                    #print '  ', row[0], row[4], filePath, diskBus, model
                    #XML内容编写
                    VMName = row[4]
                    hostName = row[0]
                    if (diskBus == 'ide'):
                        diskBusType = 'IDE 硬盘'.encode('utf-8')
                    elif (diskBus == 'usb'):
                        diskBusType = 'USB 硬盘'.encode('utf-8')
                    elif (diskBus == 'scsi'):
                        diskBusType = 'SCSI 硬盘'.encode('utf-8')
                    else:
                        diskBusType = diskBus
                    SubElement(itemXML, 'disk', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'diskPath':filePath, 'diskBusType':diskBusType})
                    index += 1
                else:
                    #print '  ', row[0], row[4], filePath, diskBus
                    #XML内容编写
                    VMName = row[4]
                    hostName = row[0]
                    if (diskBus == 'ide'):
                        diskBusType = 'IDE 硬盘'.encode('utf-8')
                    elif (diskBus == 'usb'):
                        diskBusType = 'USB 硬盘'.encode('utf-8')
                    elif (diskBus == 'scsi'):
                        diskBusType = 'SCSI 硬盘'.encode('utf-8')
                    else:
                        diskBusType = diskBus
                    SubElement(itemXML, 'disk', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'diskPath':filePath, 'diskBusType':diskBusType})
                    index += 1
        else:
            continue

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM disk bus'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机磁盘总线,结束##################################

##################################虚拟机磁盘文件是否在共享存储中,开始##################################
print "num=%s, %s: Check 'VM disk file is in share storage'. Starting" % (checkNum, getTime())
#XML文件中的检查项目说明
checkName = '检查虚拟机磁盘文件是否存放共享存储中'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "建议虚拟机磁盘文件存放在共享存储中,否则触发HA时虚拟机无法正常迁移".encode('utf-8')
itemXML = Element("diskPath",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select  host.NAME, host.IPADDR, host.HOST_USER, host.PW, volume.DOMAIN_NAME, volume.FILE_NAME, volume.POOL_PATH from TBL_STORAGE_VOLUME volume, TBL_HOST host where host.STATUS = 1 and volume.HOST_ID = host.ID order by host.NAME"

#查询数据库
cursor.execute(sql)

index = 1
hostName = ''
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    if hostName != row[0]:
        hostName = row[0]
        #通过'virsh pool-list'命令查询主机下的所有存储池的名称和状态信息
        cmd = "ssh %s 'virsh pool-list --all'" % (row[1])
        textlist = os.popen(cmd).readlines()
        lines = len(textlist)

        line = 2
        Num = 0
        poolNums = lines - 3
        poolNames = [''] * poolNums
        poolPaths = [''] * poolNums
        poolTypes = [''] * poolNums
        while line < lines - 1:
            #查询存储池名称
            findIdex = textlist[line].find(' ')
            if findIdex > -1:
                tmpPoolName = textlist[line]
                poolNames[Num] = tmpPoolName[:findIdex]
            else:
                line += 1
                continue

            #通过'virsh pool-dumpxml'命令查询主机下的所有存储池的名称和状态信息
            cmd = "ssh %s 'virsh pool-dumpxml %s'" % (row[1], poolNames[Num])
            textPools = os.popen(cmd).readlines()
            poolLines = len(textPools)
            poolLine = 0
            textPool = ''
            while poolLine < poolLines:
                textPool += textPools[poolLine]
                poolLine += 1

            root = ET.fromstring(textPool)
            poolTypes[Num] = root.get('type')

            #查询存储池路径
            for elem in root.iterfind('target/path'):
                poolPaths[Num] = elem.text

            #print '  ' + row[0], poolNames[Num], poolTypes[Num], poolPaths[Num]

            Num += 1
            line += 1

    Num = 0
    while Num < poolNums:
        if row[6] ==  poolPaths[Num]:
            if (poolTypes[Num] == 'dir') or (poolTypes[Num] == 'cifs'):
                #print '  ' + row[0], row[4], row[5], row[6], poolPaths[Num], poolTypes[Num]
                #XML内容编写
                VMName = row[4]
                hostNameTmp = row[0]
                diskPath = row[5]
                poolName = poolNames[Num]
                poolPath = poolPaths[Num]
                if (poolTypes[Num] == 'dir'):
                    poolType = '本地文件目录'.encode('utf-8')
                elif (poolTypes[Num] == 'cifs'):
                    poolType = 'Windows系统共享目录'.encode('utf-8')
                SubElement(itemXML, 'disk', {'index':str(index), 'VMName':VMName, 'hostName':hostNameTmp, 'diskPath':diskPath, 'poolName':poolName, 'poolType':poolType, 'poolPath':poolPath})
                index += 1
        Num += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM disk file is in share storage'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机磁盘文件是否在共享存储中,结束##################################

##################################虚拟机光驱,开始##################################
print "num=%s, %s: Check 'VM CDROM mount'. Starting" % (checkNum, getTime())
#XML文件中的检查项目说明
checkName = '检查虚拟机光驱是否未卸载ISO文件'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "确保虚拟机光驱未挂载ISO文件".encode('utf-8')
itemXML = Element("cdromMount",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR, host.HOST_USER, host.PW, vm.DOMAIN_NAME from TBL_HOST host, TBL_DOMAIN vm where vm.HOST_ID = host.ID and host.STATUS = 1 order by host.NAME"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #通过'virsh dumpxml'命令虚拟机配置文件信息
    cmd = "ssh %s 'virsh dumpxml %s'" % (row[1], row[4])
    textVMs = os.popen(cmd).readlines()
    VMXMLLines = len(textVMs)

    VMXMLLine = 0
    textVMXML = ''
    while VMXMLLine < VMXMLLines:
        textVMXML += textVMs[VMXMLLine]
        VMXMLLine += 1

    #print textVMXML

    root = ET.fromstring(textVMXML)
    #查询磁盘总线
    for elem in root.iterfind('devices/disk'):
        fileType = elem.get('type')
        device = elem.get('device')
        if((fileType == 'file') and (device == 'cdrom')):
            filePath = ''
            for child in elem.findall('source'):
                filePath = child.get('file')

            for child in elem.findall('target'):
                dev = child.get('dev')

            if (filePath != ''):
                #print '  ', row[0], row[4], device, filePath
                #XML内容编写
                VMName = row[4]
                hostName = row[0]
                deviceName = 'cdrom ' + dev
                SubElement(itemXML, 'cdrom', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'deviceName':deviceName, 'filePath':filePath})
                index += 1
        else:
            continue

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM CDROM mount'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机光驱,结束##################################

##################################虚拟机软驱,开始##################################
print "num=%s, %s: Check 'VM floppy mount'. Starting" % (checkNum, getTime())
checkName = '检查虚拟机是否未使用软驱设备'.encode('utf-8')
level = '一般'.encode('utf-8')
suggest = "确保虚拟机未使用软驱设备".encode('utf-8')
itemXML = Element("floppyMount",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select host.NAME, host.IPADDR, host.HOST_USER, host.PW, vm.DOMAIN_NAME from TBL_HOST host, TBL_DOMAIN vm where vm.HOST_ID = host.ID and host.STATUS = 1 order by host.NAME"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #通过'virsh dumpxml'命令虚拟机配置文件信息
    cmd = "ssh %s 'virsh dumpxml %s'" % (row[1], row[4])
    textVMs = os.popen(cmd).readlines()
    VMXMLLines = len(textVMs)

    VMXMLLine = 0
    textVMXML = ''
    while VMXMLLine < VMXMLLines:
        textVMXML += textVMs[VMXMLLine]
        VMXMLLine += 1

    #print textVMXML

    root = ET.fromstring(textVMXML)
    #查询磁盘总线
    for elem in root.iterfind('devices/disk'):
        fileType = elem.get('type')
        device = elem.get('device')
        if((fileType == 'file') and (device == 'floppy')):
            filePath = ''
            for child in elem.findall('source'):
                filePath = child.get('file')

            for child in elem.findall('target'):
                dev = child.get('dev')

            #print '  ', row[0], row[4], filePath
            #XML内容编写
            VMName = row[4]
            hostName = row[0]
            deviceName = 'floppy ' + dev
            SubElement(itemXML, 'floppy', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'deviceName':deviceName, 'filePath':filePath})
            index += 1

        else:
            continue

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM floppy mount'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机软驱,结束##################################

##################################虚拟机状态,开始##################################
print "num=%s, %s: Check 'VM status'. Starting" % (checkNum, getTime())
checkName = '检查虚拟机状态'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "确保虚拟机处于正常的运行状态".encode('utf-8')
itemXML = Element("VMState",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select vm.DOMAIN_NAME, host.NAME, vm.STATUS from TBL_DOMAIN vm, TBL_HOST host where vm.HOST_ID = host.ID and vm.STATUS <> 2 and host.STATUS = 1 order by host.NAME"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #print '  ', row[0], row[1], row[2]
    #XML内容编写
    VMName = row[0]
    hostName = row[1]
    if (row[2] == 3):
        VMState = '关闭'.encode('utf-8')
    elif (row[2] == 4):
        VMState = '暂停'.encode('utf-8')
    SubElement(itemXML, 'VM', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'VMState':VMState})
    index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM status'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机状态,结束##################################

##################################虚拟机CASTools状态,开始##################################
print "num=%s, %s: Check 'VM CAStools status'. Starting" % (checkNum, getTime())
checkName = '检查虚拟机CASTools工具状态'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "确保虚拟机安装CASTools工具,并且运行正常".encode('utf-8')
itemXML = Element("CASTools",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select vm.DOMAIN_NAME, host.NAME, vm.CASTOOLS_STATUS from TBL_DOMAIN vm, TBL_HOST host where vm.HOST_ID = host.ID and vm.STATUS = 2 and host.STATUS = 1 order by host.NAME"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    if row[2] != 1:
        #print '  ', row[0], row[1], row[2]
        #XML内容编写
        VMName = row[0]
        hostName = row[1]
        CASToolState = ''
        if (row[2] == None):
            CASToolState = '未运行'.encode('utf-8')
        elif (row[2] == 0):
            CASToolState = '未运行'.encode('utf-8')
        else:
            CASToolState = str(row[2])
        SubElement(itemXML, 'VM', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'CASToolState':CASToolState})
        index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM CAStools status'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机CASTools状态,结束##################################

##################################虚拟机CPU利用率,开始##################################
print "num=%s, %s: Check 'VM CPU use'. Starting" % (checkNum, getTime())
checkName = '检查虚拟机CPU利用率'.encode('utf-8')
level = '紧急'.encode('utf-8')
suggest = "确保虚拟机CPU利用率不超过80%".encode('utf-8')
itemXML = Element("useVMCPU",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select vm.DOMAIN_NAME, host.NAME, VMDetail.CPU_RATE, max(VMDetail.TIME) from TBL_DOMAIN_CPU_DETAIL VMDetail, TBL_DOMAIN vm, TBL_HOST host where VMDetail.DOMAIN_ID =  vm.ID and host.ID = vm.HOST_ID and vm.STATUS = 2 group by host.ID, vm.ID"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    if row[2] >= 80:
        #print '  ', row[0], row[1], row[2]
        #XML内容编写
        VMName = row[0]
        hostName = row[1]
        useVMCPU = str(row[2]) + '%'
        SubElement(itemXML, 'CPU', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'useCPU':useVMCPU})
        index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM CPU use'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机CPU利用率,结束##################################

##################################虚拟机MEM利用率,开始##################################
print "num=%s, %s: Check 'VM Memory use'. Starting" % (checkNum, getTime())
checkName = '检查虚拟机内存利用率'.encode('utf-8')
level = '紧急'.encode('utf-8')
suggest = "确保虚拟机内存利用率不超过80%".encode('utf-8')
itemXML = Element("useVMMem",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select vm.DOMAIN_NAME, host.NAME, VMDetail.MEMORY, max(VMDetail.TIME) from TBL_DOMAIN_CPU_DETAIL VMDetail, TBL_DOMAIN vm, TBL_HOST host where VMDetail.DOMAIN_ID =  vm.ID and host.ID = vm.HOST_ID and vm.STATUS = 2 group by host.ID, vm.ID"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    if row[2] >= 80:
        #print '  ', row[0], row[1], row[2]
        #XML内容编写
        VMName = row[0]
        hostName = row[1]
        useVMMem = str(row[2]) + '%'
        SubElement(itemXML, 'Memory', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'useMem':useVMMem})
        index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM Memory use'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机MEM利用率,结束##################################

##################################虚拟机磁盘利用率,开始##################################
print "num=%s, %s: Check 'VM Disk use'. Starting" % (checkNum, getTime())
checkName = '检查虚拟机磁盘利用率'.encode('utf-8')
level = '紧急'.encode('utf-8')
suggest = "确保虚拟机磁盘利用率不超过80%".encode('utf-8')
itemXML = Element("useVMDisk",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select vm.DOMAIN_NAME, host.NAME, vmDisk.DEV_NAME, vmDisk.UTILIZATION, max(vmDisk.TIME) from TBL_DOMAIN_DISK_UTILIZATION_STAT vmDisk, TBL_DOMAIN vm, TBL_HOST host where vmDisk.DOMAIN_ID =  vm.ID and host.ID = vm.HOST_ID group by host.ID, vm.ID, vmDisk.DEV_NAME"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    if row[3] >= 80:
        #print '  ', row[0], row[1], row[2], row[3]
        #XML内容编写
        VMName = row[0]
        hostName = row[1]
        diskName = row[2]
        useDisk = str(row[3]) + '%'
        SubElement(itemXML, 'Disk', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'diskName':diskName, 'useDisk':useDisk})
        index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM Disk use'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机磁盘利用率,结束##################################

##################################虚拟机磁盘分区利用率,开始##################################
print "num=%s, %s: Check 'VM Disk Partition use'. Starting" % (checkNum, getTime())
checkName = '检查虚拟机磁盘分区利用率'.encode('utf-8')
level = '紧急'.encode('utf-8')
suggest = "确保虚拟机磁盘分区利用率不超过80%".encode('utf-8')
itemXML = Element("useVMPartition",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select vm.DOMAIN_NAME, host.NAME, vmPartition.PARTITION_NAME, vmPartition.UTILIZATION, max(vmPartition.LAST_UPDATE_TIME) from TBL_DOMAIN_PARTITION_DETAIL vmPartition, TBL_DOMAIN vm, TBL_HOST host where vmPartition.DOMAIN_ID =  vm.ID and host.ID = vm.HOST_ID group by host.ID, vm.ID, vmPartition.PARTITION_NAME"

#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    if row[3] >= 80:
        #print '  ', row[0], row[1], row[2], row[3]
        #XML内容编写
        VMName = row[0]
        hostName = row[1]
        partitionName = row[2]
        usePartition = str(row[3]) + '%'
        SubElement(itemXML, 'Partition', {'index':str(index), 'VMName':VMName, 'hostName':hostName, 'partitionName':partitionName, 'usePartition':usePartition})
        index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM Disk Partition use'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机磁盘分区利用率,结束##################################

##################################虚拟机回收站,开始##################################
print "num=%s, %s: Check 'VM Recycle'. Starting" % (checkNum, getTime())
checkName = '检查虚拟机回收站配置'.encode('utf-8')
level = '一般'.encode('utf-8')
suggest = "建议虚拟机回收站不自动回收虚拟机".encode('utf-8')
itemXML = Element("Recycle",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select parameter.VALUE from TBL_PARAMETER parameter where parameter.NAME = 'vm.tombstone.lifetime'"
#查询数据库
cursor.execute(sql)
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    if int(row[0]) > 0:
        #print '  ' + 'suggest is 0'
        #XML内容编写
        lifetime = str(row[0])
        SubElement(itemXML, 'Recycle', {'lifetime':lifetime})

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM Recycle'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟机回收站,结束##################################

##################################回收站中的虚拟机,开始##################################
print "num=%s, %s: Check 'VM in Recycle'. Starting" % (checkNum, getTime())
checkName = '检查回收站中的虚拟机'.encode('utf-8')
level = '一般'.encode('utf-8')
suggest = "建议清理回收站中的虚拟机".encode('utf-8')
itemXML = Element("RecycleVM",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select vm.TITLE, vm.DOMAIN_NAME from TBL_DOMAIN vm where vm.ENABLE = 3"
#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #print '  ' + row[1]
    #XML内容编写
    VMName = row[1]
    SubElement(itemXML, 'VM', {'index':str(index), 'VMName':VMName})
    index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'VM in Recycle'. Successful" % (checkNum, getTime())
checkNum += 1
##################################回收站中的虚拟机,结束##################################

##################################虚拟共享存储配置,开始##################################
print "num=%s, %s: Check 'virtula share storage'. Starting" % (checkNum, getTime())
checkName = '检查虚拟共享存储功能配置'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "建议虚拟共享存储仅作为测试使用,实际生产环境不运行".encode('utf-8')
itemXML = Element("VirtualStorage",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select parameter.VALUE from TBL_PARAMETER parameter where parameter.NAME = 'share.system.enable'"
#查询数据库
cursor.execute(sql)
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    if int(row[0]) == 1:
        #print '  ' + 'Open the Virtual Share Storage'
        #XML内容编写
        state = '开启'.encode('utf-8')
        SubElement(itemXML, 'Storage', {'state':state})

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'virtula share storage'. Successful" % (checkNum, getTime())
checkNum += 1
##################################虚拟共享存储配置,结束##################################

##################################CVM定时备份状态,开始##################################
print "num=%s, %s: Check 'CVM backup' Status. Starting" % (checkNum, getTime())
checkName = '检查CVM定时备份功能状态'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "建议开启CVM定时备份".encode('utf-8')
itemXML = Element("CVMBackupState",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select back.STATE from TBL_BACKUP_CVM_STRATEGY back"
#查询数据库
cursor.execute(sql)
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    if int(row[0]) == 0:
        #XML内容编写
        state = '未开启CVM定时备份功能'.encode('utf-8')
        SubElement(itemXML, 'backupState', {'state':state})

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'CVM backup' Status. Successful" % (checkNum, getTime())
checkNum += 1
##################################CVM定时备份状态,结束##################################

##################################CVM备份的备份方式,开始##################################
print "num=%s, %s: Check 'CVM backup' type. Starting" % (checkNum, getTime())
checkName = '检查CVM定时备份的备份方式'.encode('utf-8')
level = '一般'.encode('utf-8')
suggest = "建议使用远程存储方式备份,不要使用主机本地目录备份".encode('utf-8')
itemXML = Element("CVMBackupType",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select back.STATE, back.STORE_MODE from TBL_BACKUP_CVM_STRATEGY back"
#查询数据库
cursor.execute(sql)
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    if (int(row[0]) == 1) and (int(row[1]) == 0):
        #print 'check the CVM Remote Backup'
        #XML内容编写
        backupPath = '主机本地目录备份'.encode('utf-8')
        SubElement(itemXML, 'backupType', {'type':backupPath})

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'CVM backup' type. Successful" % (checkNum, getTime())
checkNum += 1
##################################CVM数据备份的备份方式,结束##################################

##################################查询最30天内的操作日志信息,开始##################################
print "num=%s, %s: Check 'Operation log'. Starting" % (checkNum, getTime())
checkName = '查询最近30天内的系统操作信息'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "建议CAS系统没有无异常操作信息".encode('utf-8')
itemXML = Element("EventCAS",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select operlog.USER_NAME, operlog.DESCRIPTION, operlog.RESULT, operlog.FAILURE_REASON from TBL_OPERLOG operlog where date_sub(curdate(), INTERVAL 30 DAY) <= date(`OPER_TIME`) and operlog.USER_NAME = '$SYSTEM' and operlog.RESULT = 1 order by operlog.OPER_TIME limit 0, 50"
#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #XML内容编写
    operName = row[0]
    operDesc = row[1].encode('utf-8')
    if (row[2] == 1):
        operResult = '失败'.encode('utf-8')

    if (row[3] == None):
        operReason = ''
    else:
        operReason = row[3].encode('utf-8')

    SubElement(itemXML, 'Operate', {'index':str(index), 'name':operName, 'operDesc':str(operDesc), 'operResult':operResult, 'operReason':operReason})

    index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'Operation log'. Successful" % (checkNum, getTime())
checkNum += 1
##################################查询最近7天内的紧急和重要100条告警信息,结束##################################

##################################查询最近7天内的紧急和重要100条告警信息,开始##################################
print "num=%s, %s: Check 'Warnning log'. Starting" % (checkNum, getTime())
checkName = '查询最近7天内的紧急和重要告警信息'.encode('utf-8')
level = '重要'.encode('utf-8')
suggest = "建议CAS系统没有紧急和重要告警信息".encode('utf-8')
itemXML = Element("EventCAS",{'name':checkName, 'level':level, 'suggest':suggest})

#定义数据库查询SQL语句
sql = "select event.EVENT_NAME, event.EVENT_LEVEL, event.EVENT_DESC, event.EVENT_SRC, event.EVENT_TIME from TBL_EVENT event where event.EVENT_LEVEL <= 2 and event.STATE = 2 and date_sub(curdate(), INTERVAL 7 DAY) <= date(`EVENT_TIME`) order by event.EVENT_TIME desc limit 0, 50"
#查询数据库
cursor.execute(sql)

index = 1
while (True):
    row = cursor.fetchone()
    if row == None:
        break

    #XML内容编写
    eventName = row[0].encode('utf-8')
    if (row[1] == 1):
        eventLevel = '紧急告警'.encode('utf-8')
    elif (row[1] == 2):
        eventLevel = '重要告警'.encode('utf-8')
    eventDesc = row[2].encode('utf-8')
    eventSrc = row[3].encode('utf-8')
    eventTime = row[4]

    SubElement(itemXML, 'Event', {'index':str(index), 'name':eventName, 'eventLevel':str(eventLevel), 'eventDesc':eventDesc, 'eventSrc':eventSrc, 'eventTime':str(eventTime)})

    index += 1

#生成XML内容
purOrder.append(itemXML)

print "num=%s, %s: Check 'Warnning log'. Successful" % (checkNum, getTime())
checkNum += 1
##################################查询最近7天内的紧急和重要100条告警信息,结束##################################

cursor.close()
conn.close()

indent(purOrder)
CAS.write(filename,"utf-8",True)

print "H3C CAS-Checking Successful."
#退出巡检
exit()

 

posted on 2016-12-09 19:35  Mr.He多多指教  阅读(283)  评论(0编辑  收藏  举报