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中readline判断文件读取结束的方法
Nov 08 Python
Python中使用logging模块打印log日志详解
Apr 05 Python
玩转python爬虫之URLError异常处理
Feb 17 Python
Python实现将不规范的英文名字首字母大写
Nov 15 Python
python的构建工具setup.py的方法使用示例
Oct 23 Python
Python 机器学习库 NumPy入门教程
Apr 19 Python
python 解压pkl文件的方法
Oct 25 Python
Python3.5面向对象编程图文与实例详解
Apr 24 Python
探秘TensorFlow 和 NumPy 的 Broadcasting 机制
Mar 13 Python
python统计mysql数据量变化并调用接口告警的示例代码
Sep 21 Python
python连接mysql数据库并读取数据的实现
Sep 25 Python
python 对图片进行简单的处理
Jun 23 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+DBM的同学录程序(4)
2006/10/09 PHP
php数组函数序列之ksort()对数组的元素键名进行升序排序,保持索引关系
2011/11/02 PHP
基于php冒泡排序算法的深入理解
2013/06/09 PHP
php通过淘宝API查询IP地址归属等信息
2015/12/25 PHP
PHP开发的文字水印,缩略图,图片水印实现类与用法示例
2019/04/12 PHP
JS中Iframe之间传值的方法
2013/03/11 Javascript
NodeJS与Mysql的交互示例代码
2013/08/18 NodeJs
jqueryUI里拖拽排序示例分析
2015/02/26 Javascript
基于JS组件实现拖动滑块验证功能(代码分享)
2016/11/18 Javascript
纯原生js实现table表格的增删
2017/01/05 Javascript
jQuery插件echarts去掉垂直网格线用法示例
2017/03/03 Javascript
javascript中json对象json数组json字符串互转及取值方法
2017/04/19 Javascript
vue与TypeScript集成配置最简教程(推荐)
2017/10/17 Javascript
vue弹窗组件使用方法
2018/04/28 Javascript
JavaScript原型链与继承操作实例总结
2018/08/24 Javascript
Vue的H5页面唤起支付宝支付功能
2019/04/18 Javascript
vue实现全匹配搜索列表内容
2019/09/26 Javascript
[56:35]DOTA2上海特级锦标赛主赛事日 - 5 总决赛Liquid VS Secret第一局
2016/03/06 DOTA
[01:02:26]DOTA2-DPC中国联赛 正赛 SAG vs RNG BO3 第二场 1月18日
2021/03/11 DOTA
使用Python中的cookielib模拟登录网站
2015/04/09 Python
解决python3中解压zip文件是文件名乱码的问题
2018/03/22 Python
对Python中的@classmethod用法详解
2018/04/21 Python
win7+Python3.5下scrapy的安装方法
2018/07/31 Python
Python实现KNN(K-近邻)算法的示例代码
2019/03/05 Python
pandas基于时间序列的固定时间间隔求均值的方法
2019/07/04 Python
Pytorch 实现自定义参数层的例子
2019/08/17 Python
Python列表list操作相关知识小结
2020/01/29 Python
详解CSS3 用border写 空心三角箭头 (两种写法)
2017/09/29 HTML / CSS
怎样声明接口
2014/09/19 面试题
const char*, char const*, char*const的区别是什么
2014/07/09 面试题
创建精神文明单位实施方案
2014/03/08 职场文书
论文评语大全
2014/04/29 职场文书
传播学专业毕业生自荐书
2014/07/01 职场文书
过程装备与控制工程专业求职信
2014/07/02 职场文书
房地产营销活动策划方案
2014/09/15 职场文书
处级领导干部四风问题自我剖析材料
2014/09/29 职场文书