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中装饰器的用法
Apr 27 Python
使用Python操作MySQL的一些基本方法
Aug 16 Python
Python中使用支持向量机SVM实践
Dec 27 Python
python中ASCII码和字符的转换方法
Jul 09 Python
DataFrame:通过SparkSql将scala类转为DataFrame的方法
Jan 29 Python
python3 property装饰器实现原理与用法示例
May 15 Python
python爬虫实现中英翻译词典
Jun 25 Python
face++与python实现人脸识别签到(考勤)功能
Aug 28 Python
详解numpy矩阵的创建与数据类型
Oct 18 Python
Python 读取 YUV(NV12) 视频文件实例
Dec 09 Python
jupyter notebook 重装教程
Apr 16 Python
Python select及selectors模块概念用法详解
Jun 22 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
Discuz板块横排显示图片的实现方法
2007/05/28 PHP
php空间不支持socket但支持curl时recaptcha的用法
2011/11/07 PHP
完善CodeIgniter在IDE中代码提示功能的方法
2014/07/19 PHP
PDO防注入原理分析以及注意事项
2015/02/25 PHP
Yii2使用swiftmailer发送邮件的方法
2016/05/03 PHP
php脚本守护进程原理与实现方法详解
2017/07/20 PHP
TP5(thinkPHP5)框架使用ajax实现与后台数据交互的方法小结
2020/02/10 PHP
基于jQuery的弹出框插件
2012/03/18 Javascript
JavaScript格式化日期时间的方法和自定义格式化函数示例
2014/04/04 Javascript
Jquery实现图片预加载与延时加载的方法
2014/12/22 Javascript
javascript中clipboardData对象用法详解
2015/05/13 Javascript
JS使用eval解析JSON的注意事项分析
2015/11/14 Javascript
JavaScript编写Chrome扩展实现与浏览器的交互及时间通知
2016/05/16 Javascript
AngularJS实现ajax请求的方法
2016/11/22 Javascript
源码分析Vue.js的监听实现教程
2017/04/23 Javascript
详解Vue中一种简易路由传参办法
2017/09/15 Javascript
深入浅出vue图片路径的实现
2019/09/04 Javascript
vue中uni-app 实现小程序登录注册功能
2019/10/12 Javascript
python实现简单的socket server实例
2015/04/29 Python
python用Pygal如何生成漂亮的SVG图像详解
2017/02/10 Python
基于ID3决策树算法的实现(Python版)
2017/05/31 Python
python爬取淘宝商品详情页数据
2018/02/23 Python
Python continue继续循环用法总结
2018/06/10 Python
详解如何在PyCharm控制台中输出彩色文字和背景
2020/08/17 Python
用pip给python安装matplotlib库的详细教程
2021/02/24 Python
css3中单位px,em,rem,vh,vw,vmin,vmax的区别及浏览器支持情况
2016/12/06 HTML / CSS
Shell编程面试题
2012/05/30 面试题
最新大学毕业求职简历的自我评价
2013/10/18 职场文书
KTV的创业计划书范文
2014/02/02 职场文书
社团招新策划书
2014/02/04 职场文书
公益活动邀请函
2014/02/05 职场文书
护理助产毕业生的求职信
2014/03/02 职场文书
“三支一扶”支教教师思想汇报
2014/09/13 职场文书
学校四风问题对照检查材料思想汇报
2014/09/26 职场文书
师德标兵先进事迹材料
2014/12/19 职场文书
分家协议书范本
2016/03/22 职场文书