电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

python獲取linux系統信息的三種方法

瀏覽:25日期:2022-07-08 13:38:48

方法一:psutil模塊

#!usr/bin/env python# -*- coding: utf-8 -*-import socketimport psutilclass 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 timeimport osfrom multiprocessing import cpu_countclass 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_statprint ’==================’print nr.disk_statprint ’==================’print nr.memory_stat

方法三:subprocess

from subprocess import Popen, PIPEimport 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, PIPEimport 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 編程
相關文章:
主站蜘蛛池模板: 铣刨料沥青破碎机-沥青再生料设备-RAP热再生混合料破碎筛分设备 -江苏锡宝重工 | 奥因-光触媒除甲醛公司-除甲醛加盟公司十大品牌 | 航空障碍灯_高中低光强航空障碍灯_民航许可认证航空警示灯厂家-东莞市天翔航天科技有限公司 | 移动机器人产业联盟官网 | 拉卡拉POS机官网 - 官方直营POS机办理|在线免费领取 | cnc精密加工_数控机械加工_非标平键定制生产厂家_扬州沃佳机械有限公司 | 全钢实验台,实验室工作台厂家-无锡市辰之航装饰材料有限公司 | 喷漆房_废气处理设备-湖北天地鑫环保设备有限公司 | 薪动-人力资源公司-灵活用工薪资代发-费用结算-残保金优化-北京秒付科技有限公司 | 钢衬四氟管道_钢衬四氟直管_聚四氟乙烯衬里管件_聚四氟乙烯衬里管道-沧州汇霖管道科技有限公司 | 电表箱-浙江迈峰电力设备有限公司-电表箱专业制造商 | 北京租车公司_汽车/客车/班车/大巴车租赁_商务会议/展会用车/旅游大巴出租_北京桐顺创业租车公司 | 成都治疗尖锐湿疣比较好的医院-成都治疗尖锐湿疣那家医院好-成都西南皮肤病医院 | 回转支承-转盘轴承-回转驱动生产厂家-洛阳隆达轴承有限公司 | 热处理温控箱,热处理控制箱厂家-吴江市兴达电热设备厂 | 泰兴市热钻机械有限公司-热熔钻孔机-数控热熔钻-热熔钻孔攻牙一体机 | 柴油机_柴油发电机_厂家_品牌-江苏卡得城仕发动机有限公司 | 中矗模型-深圳中矗模型设计有限公司 | 合肥废气治理设备_安徽除尘设备_工业废气处理设备厂家-盈凯环保 合肥防火门窗/隔断_合肥防火卷帘门厂家_安徽耐火窗_良万消防设备有限公司 | 广州番禺搬家公司_天河黄埔搬家公司_企业工厂搬迁_日式搬家_广州搬家公司_厚道搬迁搬家公司 | 全球化工设备网—化工设备,化工机械,制药设备,环保设备的专业网络市场。 | 温州中研白癜风专科_温州治疗白癜风_温州治疗白癜风医院哪家好_温州哪里治疗白癜风 | 化妆品加工厂-化妆品加工-化妆品代加工-面膜加工-广东欧泉生化科技有限公司 | 耐火浇注料-喷涂料-浇注料生产厂家_郑州市元领耐火材料有限公司 耐力板-PC阳光板-PC板-PC耐力板 - 嘉兴赢创实业有限公司 | 合肥宠物店装修_合肥宠物美容院装修_合肥宠物医院设计装修公司-安徽盛世和居装饰 | 离子色谱自动进样器-青岛艾力析实验科技有限公司 | 一体化污水处理设备_生活污水处理设备_全自动加药装置厂家-明基环保 | SRRC认证|CCC认证|CTA申请_IMEI|MAC地址注册-英利检测 | 金库门,金库房,金库门厂家,金库门价格-河北特旺柜业有限公司 | 双能x射线骨密度检测仪_dxa骨密度仪_双能x线骨密度仪_品牌厂家【品源医疗】 | 合肥角钢_合肥槽钢_安徽镀锌管厂家-昆瑟商贸有限公司 | 连续油炸机,全自动油炸机,花生米油炸机-烟台茂源食品机械制造有限公司 | 无线联网门锁|校园联网门锁|学校智能门锁|公租房智能门锁|保障房管理系统-KEENZY中科易安 | 地埋式垃圾站厂家【佳星环保】小区压缩垃圾中转站转运站 | 上海办公室设计_办公楼,写字楼装修_办公室装修公司-匠御设计 | 酒店品牌设计-酒店vi设计-酒店标识设计【国际级】VI策划公司 | 半自动预灌装机,卡式瓶灌装机,注射器灌装机,给药器灌装机,大输液灌装机,西林瓶灌装机-长沙一星制药机械有限公司 | 滑板场地施工_极限运动场地设计_滑板公园建造_盐城天人极限运动场地建设有限公司 | 冷凝锅炉_燃气锅炉_工业燃气锅炉改造厂家-北京科诺锅炉 | 化妆品加工厂-化妆品加工-化妆品代加工-面膜加工-广东欧泉生化科技有限公司 | 电竞馆加盟,沈阳网吧加盟费用选择嘉棋电竞_售后服务一体化 |