python获取linux系统信息的三种方法


Posted in Python onOctober 14, 2020

方法一: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 相关文章推荐
python将xml xsl文件生成html文件存储示例讲解
Dec 03 Python
python编写的最短路径算法
Mar 25 Python
基于Python中capitalize()与title()的区别详解
Dec 09 Python
python的re正则表达式实例代码
Jan 24 Python
python使用Tesseract库识别验证
Mar 21 Python
解决Python 中英文混输格式对齐的问题
Jul 16 Python
Python找出微信上删除你好友的人脚本写法
Nov 01 Python
Python实现的各种常见分布算法示例
Dec 13 Python
python接口自动化(十七)--Json 数据处理---一次爬坑记(详解)
Apr 18 Python
基于python 等频分箱qcut问题的解决
Mar 03 Python
Python中内建模块collections如何使用
May 27 Python
python复合条件下的字典排序
Dec 18 Python
Python通过队列来实现进程间通信的示例
Oct 14 #Python
python利用xlsxwriter模块 操作 Excel
Oct 14 #Python
如何解决python多种版本冲突问题
Oct 13 #Python
Django配置Bootstrap, js实现过程详解
Oct 13 #Python
Python文件操作及内置函数flush原理解析
Oct 13 #Python
Django如何实现防止XSS攻击
Oct 13 #Python
5款实用的python 工具推荐
Oct 13 #Python
You might like
php socket方式提交的post详解
2008/07/19 PHP
PHP数组操作――获取数组最后一个值的方法
2015/04/14 PHP
js 使用form表单select类实现级联菜单效果
2012/12/19 Javascript
js为数字添加逗号并格式化数字的代码
2013/08/23 Javascript
谈谈JavaScript异步函数发展历程
2015/09/29 Javascript
JavaScript使用键盘输入控制实现数字验证功能
2016/08/19 Javascript
Angular企业级开发——MVC之控制器详解
2017/02/20 Javascript
TypeScript入门-基本数据类型
2017/03/28 Javascript
Easy UI动态树点击文字实现展开关闭功能
2017/09/30 Javascript
Bootstrap Tooltip显示换行和左对齐的解决方案
2017/10/11 Javascript
使用原生js封装的ajax实例(兼容jsonp)
2017/10/12 Javascript
编写React组件项目实践分析
2018/03/04 Javascript
vue封装一个简单的div框选时间的组件的方法
2019/01/06 Javascript
RxJS的入门指引和初步应用
2019/06/15 Javascript
Python字符串逐字符或逐词反转方法
2015/05/21 Python
Python使用redis pool的一种单例实现方式
2016/04/16 Python
Python使用QQ邮箱发送Email的方法实例
2017/02/09 Python
python测试mysql写入性能完整实例
2018/01/18 Python
读取json格式为DataFrame(可转为.csv)的实例讲解
2018/06/05 Python
pandas计数 value_counts()的使用
2019/06/24 Python
深入浅析Python 函数注解与匿名函数
2020/02/24 Python
浅析Python 简单工厂模式和工厂方法模式的优缺点
2020/07/13 Python
Python字典取键、值对的方法步骤
2020/09/30 Python
css3实现文字扫光渐变动画效果的示例
2017/11/07 HTML / CSS
你的自行车健身专家:FaFit24
2016/11/16 全球购物
芬兰汽车配件商店:Autonvaraosat24
2017/01/30 全球购物
美国女孩洋娃娃店:American Girl
2017/10/24 全球购物
Giglio俄罗斯奢侈品购物网:男士、女士、儿童高级时装
2018/07/27 全球购物
酒店中秋节促销方案
2014/01/30 职场文书
本科毕业生应聘求职信
2014/07/06 职场文书
公证委托书格式
2014/09/13 职场文书
父亲婚礼答谢词
2015/01/04 职场文书
委托书格式要求
2015/01/28 职场文书
2015年第十五个全民国防教育日宣传活动方案
2015/05/06 职场文书
background-position百分比原理详解
2021/05/08 HTML / CSS
JDBC连接的六步实例代码(与mysql连接)
2021/05/12 MySQL