方法一:psutil模块
#!usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import psutil
class NodeResource(object):
def get_host_info(self):
host_name = socket.gethostname()
return {"host_name":host_name}
def get_cpu_state(self):
cpu_count = psutil.cpu_count(logical=False)
cpu_percent =(str)(psutil.cpu_percent(1))+"%"
return {"cpu_count":cpu_count,"cpu_percent":cpu_percent}
def get_memory_state(self):
mem = psutil.virtual_memory()
mem_total = mem.total / 1024 / 1024
mem_free = mem.available /1024/1024
mem_percent = "%s%%"%mem.percent
return {"mem_toal":mem_total,"mem_free":mem_free,"mem_percent":mem_percent}
def get_disk_state(self):
disk_stat = psutil.disk_usage("/")
disk_total = disk_stat.total
disk_free = disk_stat.free
disk_percent = "%s%%"%disk_stat.percent
return {"mem_toal": disk_total, "mem_free": disk_free, "mem_percent": disk_percent}
方法二:proc
#!usr/bin/env python
# -*- coding: utf-8 -*-
import time
import os
from multiprocessing import cpu_count
class NodeResource(object):
def usage_percent(self,use, total):
# 返回百分占比
try:
ret = int(float(use)/ total * 100)
except ZeroDivisionError:
raise Exception("ERROR - zero division error")
return "%s%%"%ret
@property
def cpu_stat(self,interv