python获取linux系统信息的三种方法
方法一:psutil模块
#!usr/bin/envpython #-*-coding:utf-8-*- importsocket importpsutil classNodeResource(object): defget_host_info(self): host_name=socket.gethostname() return{'host_name':host_name} defget_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} defget_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} defget_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/envpython #-*-coding:utf-8-*- importtime importos frommultiprocessingimportcpu_count classNodeResource(object): defusage_percent(self,use,total): #返回百分占比 try: ret=int(float(use)/total*100) exceptZeroDivisionError: raiseException("ERROR-zerodivisionerror") return'%s%%'%ret @property defcpu_stat(self,interval=1): cpu_num=cpu_count() withopen("/proc/stat","r")asf: line=f.readline() spl=line.split("") worktime_1=sum([int(i)foriinspl[2:]]) idletime_1=int(spl[5]) time.sleep(interval) withopen("/proc/stat","r")asf: line=f.readline() spl=line.split("") worktime_2=sum([int(i)foriinspl[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 defdisk_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']) returnhd @property defmemory_stat(self): mem={} withopen("/proc/meminfo")asf: forlineinf: line=line.strip() iflen(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() printnr.cpu_stat print'==================' printnr.disk_stat print'==================' printnr.memory_stat
方法三:subprocess
fromsubprocessimportPopen,PIPE importos,sys '''获取ifconfig命令的输出''' defgetIfconfig(): p=Popen(['ifconfig'],stdout=PIPE) data=p.stdout.read() returndata '''获取dmidecode命令的输出''' defgetDmi(): p=Popen(['dmidecode'],stdout=PIPE) data=p.stdout.read() returndata '''根据空行分段落返回段落列表''' defparseData(data): parsed_data=[] new_line='' data=[iforiindata.split('\n')ifi] forlineindata: ifline[0].strip(): parsed_data.append(new_line) new_line=line+'\n' else: new_line+=line+'\n' parsed_data.append(new_line) return[iforiinparsed_dataifi] '''根据输入的段落数据分析出ifconfig的每个网卡ip信息''' defparseIfconfig(parsed_data): dic={} parsed_data=[iforiinparsed_dataifnoti.startswith('lo')] forlinesinparsed_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 returndic '''根据输入的dmi段落数据分析出指定参数''' defparseDmi(parsed_data): dic={} parsed_data=[iforiinparsed_dataifi.startswith('SystemInformation')] parsed_data=[iforiinparsed_data[0].split('\n')[1:]ifi] dmi_dic=dict([i.strip().split(':')foriinparsed_data]) dic['vender']=dmi_dic['Manufacturer'].strip() dic['product']=dmi_dic['ProductName'].strip() dic['sn']=dmi_dic['SerialNumber'].strip() returndic '''获取Linux系统主机名称''' defgetHostname(): withopen('/etc/sysconfig/network')asfd: forlineinfd: ifline.startswith('HOSTNAME'): hostname=line.split('=')[1].strip() break return{'hostname':hostname} '''获取Linux系统的版本信息''' defgetOsVersion(): withopen('/etc/issue')asfd: forlineinfd: osver=line.strip() break return{'osver':osver} '''获取CPU的型号和CPU的核心数''' defgetCpu(): num=0 withopen('/proc/cpuinfo')asfd: forlineinfd: ifline.startswith('processor'): num+=1 ifline.startswith('modelname'): 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系统的总物理内存''' defgetMemory(): withopen('/proc/meminfo')asfd: forlineinfd: ifline.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) '''将获取到的所有数据信息并按简单格式对齐显示''' fork,vindic.items(): print'%-10s:%s'%(k,v)
fromsubprocessimportPopen,PIPE importtime '''获取ifconfig命令的输出''' #defgetIfconfig(): #p=Popen(['ipconfig'],stdout=PIPE) #data=p.stdout.read() #data=data.decode('cp936').encode('utf-8') #returndata # #print(getIfconfig()) p=Popen(['top-n2-d|grepCpu'],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])) printcpu_percent
以上就是python获取linux系统信息的三种方法的详细内容,更多关于python获取linux系统信息的资料请关注毛票票其它相关文章!