python获取linux系统信息的三种示例
更新时间:2020年10月14日 13:18 点击:1824
方法一: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,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
方法三: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)
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
以上就是python获取linux系统信息的三种示例的详细内容,更多关于python获取linux系统信息的资料请关注猪先飞其它相关文章!
相关文章
- 这篇文章主要介绍了python-opencv-画外接矩形框的实例代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-04
Python astype(np.float)函数使用方法解析
这篇文章主要介绍了Python astype(np.float)函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-08- 2022虎年新年即将来临,小编为大家带来了一个利用Python编写的虎年烟花特效,堪称全网最绚烂,文中的示例代码简洁易懂,感兴趣的同学可以动手试一试...2022-02-14
- 在本篇文章里小编给大家分享的是一篇关于python中numpy.empty()函数实例讲解内容,对此有兴趣的朋友们可以学习下。...2021-02-06
python-for x in range的用法(注意要点、细节)
这篇文章主要介绍了python-for x in range的用法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-05-10- 这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
- 这篇文章主要介绍了Python中的imread()函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-16
- 这篇文章主要介绍了python如何实现b站直播自动发送弹幕,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下...2021-02-20
- 这篇文章主要介绍了Vue基于localStorage存储信息代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-11-16
python Matplotlib基础--如何添加文本和标注
这篇文章主要介绍了python Matplotlib基础--如何添加文本和标注,帮助大家更好的利用Matplotlib绘制图表,感兴趣的朋友可以了解下...2021-01-26- 这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
- 今天小编就为大家分享一篇python 计算方位角实例(根据两点的坐标计算),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-04-27
- 这篇文章主要为大家详细介绍了python实现双色球随机选号,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-05-02
- 在本篇文章里小编给大家整理的是一篇关于python中使用np.delete()的实例方法,对此有兴趣的朋友们可以学习参考下。...2021-02-01
- 这篇文章主要介绍了使用Python的pencolor函数实现渐变色功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-09
- 这篇文章主要介绍了python自动化办公操作PPT的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-05
Python getsizeof()和getsize()区分详解
这篇文章主要介绍了Python getsizeof()和getsize()区分详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-20- 这篇文章主要为大家详细介绍了python实现学生通讯录管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-25
- 这篇文章主要介绍了PyTorch一小时掌握之迁移学习篇,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-08
- 网上文章中,在linux下安装node.js都是使用源码编译,其实node的github上已经提供了各个系统下使用各自的包管理器(package manager)安装node.js的方法。...2015-03-15