用Python获取Linux资源信息的三种方法
方法一: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}
psutil
方法二:、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,interval = 1): cpu_num = cpu_count()
with open("/proc/stat", "r") as f:
line = f.readline()
spl = line.split(" ")
worktime_1 = sum([int(i) for i in spl[2:]])
idletime_1 = int(spl[5])
time.sleep(interval)
with open("/proc/stat", "r") as f:
line = f.readline()
spl = line.split(" ")
worktime_2 = sum([int(i) for i in spl[2:]])
idletime_2 = int(spl[5]) dworktime = (worktime_2 - worktime_1)
didletime = (idletime_2 - idletime_1)
cpu_percent = self.usage_percent(dworktime - didletime,didletime)
return {'cpu_count':cpu_num,'cpu_percent':cpu_percent} @property
def disk_stat(self):
hd = {}
disk = os.statvfs("/")
hd['available'] = disk.f_bsize * disk.f_bfree
hd['capacity'] = disk.f_bsize * disk.f_blocks
hd['used'] = hd['capacity'] - hd['available']
hd['used_percent'] = self.usage_percent(hd['used'], hd['capacity'])
return hd @property
def memory_stat(self):
mem = {}
with open("/proc/meminfo") as f:
for line in f:
line = line.strip()
if len(line) < 2: continue
name = line.split(':')[0]
var = line.split(':')[1].split()[0]
mem[name] = long(var) * 1024.0
mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached']
mem['used_percent'] = self.usage_percent(mem['MemUsed'],mem['MemTotal'])
return {'MemUsed':mem['MemUsed'],'MemTotal':mem['MemTotal'],'used_percent':mem['used_percent']} nr = NodeResource() print nr.cpu_stat
print '=================='
print nr.disk_stat
print '=================='
print nr.memory_stat
proc
方法三:subprocess
from subprocess import Popen, PIPE
import os,sys ''' 获取 ifconfig 命令的输出 '''
def getIfconfig():
p = Popen(['ifconfig'], stdout = PIPE)
data = p.stdout.read()
return data ''' 获取 dmidecode 命令的输出 '''
def getDmi():
p = Popen(['dmidecode'], stdout = PIPE)
data = p.stdout.read()
return data ''' 根据空行分段落 返回段落列表'''
def parseData(data):
parsed_data = []
new_line = ''
data = [i for i in data.split('\n') if i]
for line in data:
if line[0].strip():
parsed_data.append(new_line)
new_line = line + '\n'
else:
new_line += line + '\n'
parsed_data.append(new_line)
return [i for i in parsed_data if i] ''' 根据输入的段落数据分析出ifconfig的每个网卡ip信息 '''
def parseIfconfig(parsed_data):
dic = {}
parsed_data = [i for i in parsed_data if not i.startswith('lo')]
for lines in parsed_data:
line_list = lines.split('\n')
devname = line_list[0].split()[0]
macaddr = line_list[0].split()[-1]
ipaddr = line_list[1].split()[1].split(':')[1]
break
dic['ip'] = ipaddr
return dic ''' 根据输入的dmi段落数据 分析出指定参数 '''
def parseDmi(parsed_data):
dic = {}
parsed_data = [i for i in parsed_data if i.startswith('System Information')]
parsed_data = [i for i in parsed_data[0].split('\n')[1:] if i]
dmi_dic = dict([i.strip().split(':') for i in parsed_data])
dic['vender'] = dmi_dic['Manufacturer'].strip()
dic['product'] = dmi_dic['Product Name'].strip()
dic['sn'] = dmi_dic['Serial Number'].strip()
return dic ''' 获取Linux系统主机名称 '''
def getHostname():
with open('/etc/sysconfig/network') as fd:
for line in fd:
if line.startswith('HOSTNAME'):
hostname = line.split('=')[1].strip()
break
return {'hostname':hostname} ''' 获取Linux系统的版本信息 '''
def getOsVersion():
with open('/etc/issue') as fd:
for line in fd:
osver = line.strip()
break
return {'osver':osver} ''' 获取CPU的型号和CPU的核心数 '''
def getCpu():
num = 0
with open('/proc/cpuinfo') as fd:
for line in fd:
if line.startswith('processor'):
num += 1
if line.startswith('model name'):
cpu_model = line.split(':')[1].strip().split()
cpu_model = cpu_model[0] + ' ' + cpu_model[2] + ' ' + cpu_model[-1]
return {'cpu_num':num, 'cpu_model':cpu_model} ''' 获取Linux系统的总物理内存 '''
def getMemory():
with open('/proc/meminfo') as fd:
for line in fd:
if line.startswith('MemTotal'):
mem = int(line.split()[1].strip())
break
mem = '%.f' % (mem / 1024.0) + ' MB'
return {'Memory':mem} if __name__ == '__main__':
dic = {}
data_ip = getIfconfig()
parsed_data_ip = parseData(data_ip)
ip = parseIfconfig(parsed_data_ip) data_dmi = getDmi()
parsed_data_dmi = parseData(data_dmi)
dmi = parseDmi(parsed_data_dmi) hostname = getHostname()
osver = getOsVersion()
cpu = getCpu()
mem = getMemory() dic.update(ip)
dic.update(dmi)
dic.update(hostname)
dic.update(osver)
dic.update(cpu)
dic.update(mem) ''' 将获取到的所有数据信息并按简单格式对齐显示 '''
for k,v in dic.items():
print '%-10s:%s' % (k, v)
pipe,poen
from subprocess import Popen, PIPE
import time ''' 获取 ifconfig 命令的输出 '''
# def getIfconfig():
# p = Popen(['ipconfig'], stdout = PIPE)
# data = p.stdout.read()
# data = data.decode('cp936').encode('utf-8')
# return data
#
# print(getIfconfig()) p = Popen(['top -n 2 -d |grep Cpu'],stdout= PIPE,shell=True)
data = p.stdout.read()
info = data.split('\n')[1]
info_list = info.split()
cpu_percent ='%s%%'%int(float(info_list[1])+float(info_list[3]))
print cpu_percent
top+Popen
用Python获取Linux资源信息的三种方法的更多相关文章
- php获取网页header信息的4种方法
php获取网页header信息的方法多种多样,就php语言来说,我知道的方法有4种, 下面逐一献上. 方法一:使用get_headers()函数 推荐指数: ★★★★★ get_header方法最简单 ...
- python每次处理一个字符的三种方法
python每次处理一个字符的三种方法 a_string = "abccdea" print 'the first' for c in a_string: print ord(c) ...
- PHP获取文件后缀名的三种方法
如下: <? PHP获取文件后缀名的几种方法1: function get_file_type($filename){ $type = substr($filename, strrpos($fi ...
- python获取网页信息的三种方法
import urllib.request import http.cookiejar url = 'http://www.baidu.com/' # 方法一 print('方法一') req_one ...
- python 获取本机IP的三种方式
python获取本机IP的方式 第一种: #!/usr/bin/python import socket import fcntl import struct def get_ip_address(i ...
- Linux 下系统调用的三种方法
系统调用(System Call)是操作系统为在用户态运行的进程与硬件设备(如CPU.磁盘.打印机等)进行交互提供的一组接口.当用户进程需要发生系统调用时,CPU 通过软中断切换到内核态开始执行内核系 ...
- Python 文件行数读取的三种方法
Python三种文件行数读取的方法: #文件比较小 count = len(open(r"d:\lines_test.txt",'rU').readlines()) print c ...
- Python 判断文件是否存在的三种方法
通常在读写文件之前,需要判断文件或目录是否存在,不然某些处理方法可能会使程序出错.所以最好在做任何操作之前,先判断文件是否存在. 这里将介绍三种判断文件或文件夹是否存在的方法,分别使用os模块.Try ...
- python webdriver api-上传文件的三种方法
上传文件: 第一种方式,sendkeys(),最简单的 #encoding=utf-8 from selenium import webdriver import unittest import ti ...
随机推荐
- spring各种邮件发送
参考地址一 参考地址二 参考地址三 参考地址四 Spring邮件抽象层的主要包为org.springframework.mail.它包括了发送电子邮件的主要接口MailSender,和值对象Simpl ...
- Linux-yum在线安装svn步骤
yum -y install subversion httpd mod_dav_svn 使用yum命令安装svn(subversion),httpd(apache服务器)和svn在apache上的插件 ...
- .net mvc 站点自带简易SSL加密传输 Word报告自动生成(例如 导出数据库结构) 微信小程序:动画(Animation) SignalR 设计理念(一) ASP.NET -- WebForm -- ViewState ASP.NET -- 一般处理程序ashx 常用到的一些js方法,记录一下 CryptoJS与C#AES加解密互转
.net mvc 站点自带简易SSL加密传输 因项目需要,传输数据需要加密,因此有了一些经验,现简易抽出来分享! 请求:前端cryptojs用rsa/aes 或 rsa/des加密,后端.net ...
- 设置或者得到CheckBoxList选中了的值
在项目中我们可能会经常遇到一收集多选信息的情况,比如做注册的时候要收集个人爱好,那时候大家第一个想到的肯定是CheckBoxList.那我们怎么来获取到CheckBoxList的值并且存入数据库呢?? ...
- C# 文件与路径操作
OpenFileDialog private void btnOpenFileDialog_Click(object sender, EventArgs e) { OpenFileDialog ope ...
- spring in action小结3 运行时值注入
讨论依赖注入的时候,通常讨论的是一个bean引用注入到另一个bean的属性或者构造器参数中.bean装配的另一个方面是将值注入到bean的属性或者构造器参数中.避免硬编码的方式就是运行时确定值. sp ...
- unity, yield return new WaitForSeconds(waitTime) 在 Time.timeScale=0下卡死
例如下面代码: IEnumerator f(){ Time.timeScale = 0; float waitTime=2; yield return new WaitForSeconds (wait ...
- [Jobdu] 题目1408:吃豆机器人
题目描述: 淘宝公司内部有许多新鲜的小玩具,例如淘宝智能机器人.小时候,大家都玩过那个吃豆子的游戏吧,这机器人就是按照这个游戏设计的,它会朝着豆子的方向行走.不过机器人还存在一个bug,他只会朝南和朝 ...
- OC06 -- 字典
一. 创建不可变字典的方式: //字典的字面量,前key后value NSDictionary *dic =@{@"1":@"2",@"3" ...
- 信号处理函数(1)-alarm定时器
定义: unsigned int alarm(unsigned int seconds); 表头文件: #include<unistd.h> 说明: alarm()用来设置信号SI ...