python 获取资源信息

 #!/usr/bin/env python

#-*-coding:utf8-*-
"""
@Author :  Villiam Sheng
@Group  :  Linux Group
@Date   :  2012-07-18
@Funtion:
            Update kvm host status ...
            get_nic: Get a week network flow
                1,Get Seven days before flow,get maximum value!
                2,Get Seven days before flow,get average value!
 
"""
import os,sys,libvirt,socket,shutil,re
from  statvfs import F_BLOCKS,F_BAVAIL,F_BSIZE
 
class kvm_os_status(object):
    def __init__(self):
        self.vmm = {}
        try:
            self.conn = libvirt.open(None)
        except libvirt.libvirtError,e:
            print e
 
    def get_mem(self):
        try:
            f = open('/proc/meminfo','r')
            for i in f.readlines():
                if i.find('MemTotal:') != -1:
                    total_mem=int(i.split(':')[1].split('kB')[0])/1024
                    continue
            try:
                exec_command = """ grep "memory" /data*/domains/*/*.xml 2>/dev/null |awk -F "<memory>" '{print $2}'|awk -F "</memory>" '{print $1}' """
                mem = os.popen(exec_command).readlines()
                act_mem = 0
                for m in mem:
                    act_mem += int(m) / 1024
                self.vmm['free_mem'] = total_mem - act_mem
            except Exception,e:
                pass
        except Exception,e:
            pass
 
    def get_mip(self):
        try:
            exec_command = """cat /etc/sysconfig/network-scripts/ifcfg-br0 |grep "IPADDR"|awk -F"=" '{print $2}' 2>/dev/null"""
            mip = os.popen(exec_command).read().strip()
            sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
            try:
                sock.connect((mip,0))
            except socket.error,e:
                exec_command = """cat /etc/sysconfig/network-scripts/ifcfg-br1 |grep "IPADDR"|awk -F"=" '{print $2}'"""
                nip = os.popen(exec_command).read().strip()
                self.vmm['mip'] = nip
            self.vmm['mip'] = sock.getsockname()[0]
        except:
            pass
 
 
    def get_disk(self):
        extends = []
        disk={}
        try:
            ext_disk = os.popen("df -h |awk '{print $1,$6}'|grep -v 'tmpfs'|grep -v 'Filesystem'|grep -v 'sda1'|grep -v 'mfs'|grep -v 'T'").readlines()
        except Exception,e:
            print e
        if ext_disk == "":
            self.vmm['free_disk'] = vfs[F_BLOCKS]*vfs[F_BSIZE]/1024/1024/1024
        else:
            free_disk = 0
            for disk in ext_disk:
                try:
                    vfs = os.statvfs(disk.split()[1])
                except Exception,e:
                    print e
                full_space = vfs[F_BLOCKS]*vfs[F_BSIZE]/1024/1024/1024
                free_space = vfs[F_BAVAIL]*vfs[F_BSIZE]/1024/1024/1024
                imgs = os.popen("ls -ls %s/domains/vm*/data*.img 2>/dev/null | awk '{print $1,$6}'" % disk.split()[1]).readlines()
                if imgs:
                    for i in imgs:
                        t_size, f_size = i.strip().split()
                        free_space -= int(f_size)/1024/1024/1024
                        if int(t_size) != 0:
                            free_space += int(t_size)/1024/1024
                disk={disk.split()[1]:free_space}
                for i in disk.keys():
                    free_disk += disk[i]
            self.vmm['free_disk'] = free_disk
            a = os.popen("cat /etc/issue|awk '{print $7}'|grep -v 'Kernel'|grep -v '^$'").readline()
            self.vmm['os_type'] = 'RHEL%sx64'%a.strip()
 
    def count(self):
        self.vmm['vmm_count'] = 0
        try:
            for id in self.conn.listDomainsID():
                dom = self.conn.lookupByID(id)
                self.vmm['vmm_count'] = self.vmm['vmm_count'] + 1
        except libvirt.libvirtError,e:
            pass
        print self.vmm
    def work(self):
        self.get_mem()
        self.get_disk()
        self.get_mip()
        self.count()
 
if __name__ == "__main__":
    st = kvm_os_status()
    st.work()
 

本文出自 “欢迎评论,欢迎点赞” 博客,谢绝转载!

你可能感兴趣的:(python,kvm,disk,mem)