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写的英文字符大小写转换代码示例
Mar 06 Python
Python实现在线程里运行scrapy的方法
Apr 07 Python
pygame游戏之旅 添加icon和bgm音效的方法
Nov 21 Python
python 用所有标点符号分隔句子的示例
Jul 15 Python
python3在同一行内输入n个数并用列表保存的例子
Jul 20 Python
Python 识别12306图片验证码物品的实现示例
Jan 20 Python
PyCharm如何导入python项目的方法
Feb 06 Python
详解python itertools功能
Feb 07 Python
python实现图片横向和纵向拼接
Mar 05 Python
python实现在线翻译
Jun 18 Python
使用AJAX和Django获取数据的方法实例
Oct 25 Python
Python爬虫爬取全球疫情数据并存储到mysql数据库的步骤
Mar 29 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 CLI模式下的多进程应用分析
2013/06/03 PHP
php curl模拟post请求小实例
2013/11/13 PHP
destoon后台网站设置变成空白的解决方法
2014/06/21 PHP
php使用escapeshellarg时中文被过滤的解决方法
2016/07/10 PHP
thinkPHP自定义类实现方法详解
2016/11/30 PHP
php批量转换文件夹下所有文件编码的函数类
2017/08/06 PHP
javascript中的几个运算符
2007/06/29 Javascript
jquery插件之easing 动态菜单
2010/08/21 Javascript
jQuery中Ajax的load方法详解
2015/01/14 Javascript
JavaScript判断数组是否包含指定元素的方法
2015/07/01 Javascript
JS实现自动定时切换的简洁网页选项卡效果
2015/10/13 Javascript
易操作的jQuery表单提示插件
2015/12/01 Javascript
D3.js封装文本实现自动换行和旋转平移等功能
2016/10/14 Javascript
JavaScript正则表达式小结(test|match|search|replace|split|exec)
2016/12/08 Javascript
微信小程序 MinUI组件库系列之badge徽章组件示例
2018/08/20 Javascript
js最实用string(字符串)类型的使用及截取与拼接详解
2019/04/26 Javascript
Nodejs异步流程框架async的方法
2019/06/07 NodeJs
给Python入门者的一些编程建议
2015/06/15 Python
浅谈python中set使用
2016/06/30 Python
使用python实现抓取腾讯视频所有电影的爬虫
2019/04/15 Python
python递归法解决棋盘分割问题
2019/07/17 Python
python飞机大战pygame游戏背景设计详解
2019/12/17 Python
python通过nmap扫描在线设备并尝试AAA登录(实例代码)
2019/12/30 Python
keras CNN卷积核可视化,热度图教程
2020/06/22 Python
python判断元素是否存在的实例方法
2020/09/24 Python
python Zmail模块简介与使用示例
2020/12/19 Python
Python 实现一个简单的web服务器
2021/01/03 Python
CSS3 Media Queries(响应式布局可以让你定制不同的分辨率和设备)
2013/06/06 HTML / CSS
接口的多继承会带来哪些问题
2015/08/17 面试题
高中学生干部学习的自我评价
2014/02/21 职场文书
教师考核材料
2014/05/21 职场文书
学校学习雷锋活动总结
2014/07/03 职场文书
向国旗敬礼活动总结
2014/09/27 职场文书
2014年财务工作总结与计划
2014/12/08 职场文书
学生会干部任命书
2015/09/21 职场文书
2016年学习贯彻十八届五中全会精神心得体会
2016/01/05 职场文书