python獲取linux系統(tǒng)信息的三種方法
更新時間: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的每個網(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的型號和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ù)信息并按簡單格式對齊顯示 '''
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)信息的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:
- Bash 腳本實(shí)現(xiàn)每次登錄到 Shell 時可以查看 Linux 系統(tǒng)信息
- 使用 Python 獲取 Linux 系統(tǒng)信息的代碼
- Linux系統(tǒng)信息查看常用命令
- Linux、ubuntu系統(tǒng)下查看顯卡型號、顯卡信息詳解
- Linux系統(tǒng)查看CPU、機(jī)器型號、內(nèi)存等信息
- 使用Python獲取Linux系統(tǒng)的各種信息
- 詳解linux下查看系統(tǒng)版本號信息的方法(總結(jié))
- 使用python獲取CPU和內(nèi)存信息的思路與實(shí)現(xiàn)(linux系統(tǒng))
- linux系統(tǒng)獲取硬盤使用信息
- Linux系統(tǒng)下利用C程序輸出某進(jìn)程的內(nèi)存占用信息
- linux系統(tǒng)使用python獲取cpu信息腳本分享
- linux如何查看系統(tǒng)信息
相關(guān)文章
python實(shí)戰(zhàn)練習(xí)之最新男女顏值打分小系統(tǒng)
前幾天不是出過一期Python美顏相機(jī)嘛?不知道大家現(xiàn)在還記不記得?這一期的話題還是緊接著那一期顏值方面來走,對大家的學(xué)習(xí)或工作具有一定的價(jià)值,需要的朋友可以參考下2021-09-09
Python實(shí)現(xiàn)曲線點(diǎn)抽稀算法的示例
本篇文章主要介紹了Python實(shí)現(xiàn)曲線點(diǎn)抽稀算法的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
python實(shí)現(xiàn)遞歸查找某個路徑下所有文件中的中文字符
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)遞歸查找某個路徑下所有文件中的中文字符,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-08-08
利用Python實(shí)現(xiàn)網(wǎng)站自動簽到
小五收藏了一些論壇網(wǎng)站,經(jīng)常需要自己登錄簽到,以此來獲得積分金幣等等。但天天手動太容易忘了這件事啦。畢竟我們都會用python了,那就可以使用Selenium操作,接下來就和大家講講如何利用Python實(shí)現(xiàn)網(wǎng)站自動簽到2022-08-08

