相思资源网 Design By www.200059.com

方法一: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,获取Linux信息

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

评论“python获取linux系统信息的三种方法”

暂无python获取linux系统信息的三种方法的评论...

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。