最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python獲取linux系統(tǒng)信息的三種方法

 更新時(shí)間:2020年10月14日 09:54:01   作者:Python探索牛  
這篇文章主要介紹了python獲取linux系統(tǒng)信息的三種方法,幫助大家利用python了解自己的系統(tǒng)詳情,感興趣的朋友可以了解下

方法一: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

''' 根據(jù)空行分段落 返回段落列表'''
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]

''' 根據(jù)輸入的段落數(shù)據(jù)分析出ifconfig的每個(gè)網(wǎng)卡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

''' 根據(jù)輸入的dmi段落數(shù)據(jù) 分析出指定參數(shù) '''
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系統(tǒng)主機(jī)名稱 '''
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系統(tǒng)的版本信息 '''
def getOsVersion():
 with open('/etc/issue') as fd:
  for line in fd:
   osver = line.strip()
   break
 return {'osver':osver}

''' 獲取CPU的型號(hào)和CPU的核心數(shù) '''
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系統(tǒng)的總物理內(nèi)存 '''
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)

 ''' 將獲取到的所有數(shù)據(jù)信息并按簡(jiǎn)單格式對(duì)齊顯示 '''
 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系統(tǒng)信息的三種方法的詳細(xì)內(nèi)容,更多關(guān)于python獲取linux系統(tǒng)信息的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python xlwings插入Excel圖片的實(shí)現(xiàn)方法

    Python xlwings插入Excel圖片的實(shí)現(xiàn)方法

    這篇文章主要介紹了Python xlwings插入Excel圖片的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • Python生成ubuntu apt鏡像地址實(shí)現(xiàn)

    Python生成ubuntu apt鏡像地址實(shí)現(xiàn)

    本文主要介紹了Python生成ubuntu apt鏡像地址實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05
  • python Web開(kāi)發(fā)你要理解的WSGI & uwsgi詳解

    python Web開(kāi)發(fā)你要理解的WSGI & uwsgi詳解

    這篇文章主要給大家介紹了關(guān)于python Web開(kāi)發(fā)你一定要理解的WSGI & uwsgi的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-08-08
  • Pytorch中的masked_fill基本知識(shí)詳解

    Pytorch中的masked_fill基本知識(shí)詳解

    本文介紹了PyTorch中masked_fill函數(shù)的基本使用和原理,該函數(shù)接受一個(gè)輸入張量和一個(gè)布爾掩碼作為參數(shù),掩碼的形狀必須與輸入張量相同,True表示需要填充的位置,False表示保持原值
    2024-10-10
  • 云原生Docker部署Django和mysql項(xiàng)目全過(guò)程

    云原生Docker部署Django和mysql項(xiàng)目全過(guò)程

    最近在學(xué)習(xí)用docker部署Django項(xiàng)目,經(jīng)過(guò)百折不撓的鼓搗,終于將項(xiàng)目部署成功,下面這篇文章主要給大家介紹了關(guān)于云原生Docker部署Django和mysql項(xiàng)目的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2022-12-12
  • 利用scrapy將爬到的數(shù)據(jù)保存到mysql(防止重復(fù))

    利用scrapy將爬到的數(shù)據(jù)保存到mysql(防止重復(fù))

    這篇文章主要給大家介紹了關(guān)于利用scrapy將爬到的數(shù)據(jù)保存到mysql(防止重復(fù))的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。
    2018-03-03
  • Python求算數(shù)平方根和約數(shù)的方法匯總

    Python求算數(shù)平方根和約數(shù)的方法匯總

    這篇文章主要介紹了 Python求算數(shù)平方根和約數(shù)的方法匯總的相關(guān)資料,需要的朋友可以參考下
    2016-03-03
  • Python語(yǔ)法分析之字符串格式化

    Python語(yǔ)法分析之字符串格式化

    這篇文章主要給大家介紹了關(guān)于Python語(yǔ)法分析之字符串格式化的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • python logging重復(fù)記錄日志問(wèn)題的解決方法

    python logging重復(fù)記錄日志問(wèn)題的解決方法

    python的logging模塊是python使用過(guò)程中打印日志的利器,下面這篇文章主要給大家介紹了關(guān)于python logging重復(fù)記錄日志問(wèn)題的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2018-07-07
  • Java文件與類(lèi)動(dòng)手動(dòng)腦實(shí)例詳解

    Java文件與類(lèi)動(dòng)手動(dòng)腦實(shí)例詳解

    在本篇文章里小編給大家整理的是關(guān)于Java文件與類(lèi)動(dòng)手動(dòng)腦實(shí)例知識(shí)點(diǎn),有需要的朋友們學(xué)習(xí)參考下。
    2019-11-11

最新評(píng)論

康乐县| 四子王旗| 施甸县| 漠河县| 溆浦县| 酒泉市| 新民市| 五寨县| 隆尧县| 财经| 固镇县| 霍林郭勒市| 桂阳县| 名山县| 贵溪市| 凤阳县| 灵台县| 乳山市| 阿坝| 湘西| 紫阳县| 汤阴县| 外汇| 连城县| 邵武市| 若尔盖县| 安福县| 白城市| 恭城| 渑池县| 囊谦县| 忻城县| 太仓市| 安化县| 宁武县| 泰和县| 三原县| 南城县| 开江县| 福贡县| 阿克陶县|