通过 dmidecode 命令可以获取到 Linux 系统的包括 BIOS、 CPU、内存等系统的硬件信息,这里使用 python 代码来通过调用 dmidecode 命令来获取 Linux 必要的系统信息,更多的信息都可以通过这种方式去获取。
方式1:
1 #!/usr/bin/python 2 #encoding: utf-8 3 4 from subprocess import Popen, PIPE 5 6 p = Popen([‘dmidecode‘], stdout = PIPE) 7 data = p.stdout 8 lines = [] 9 dicts = {} 10 11 while True: 12 line = data.readline() 13 if line.startswith(‘System Information‘): 14 while True: 15 line = data.readline() 16 if line == ‘\n‘: 17 break 18 else: 19 lines.append(line) 20 break 21 22 d = dict([i.strip().split(‘:‘) for i in lines]) 23 24 #for k,v in dicts.items(): 25 # dicts[k] = v.strip() 26 dicts[‘Manufacturer‘] = d[‘Manufacturer‘].strip() 27 dicts[‘Product Name‘] = d[‘Product Name‘].strip() 28 dicts[‘Serial Number‘] = d[‘Serial Number‘].strip() 29 print dicts
方式2:
1 #!/usr/bin/python 2 #encoding: utf-8 3 4 from subprocess import Popen, PIPE 5 6 def getDmi(): 7 p = Popen([‘dmidecode‘], stdout = PIPE) 8 data = p.stdout.read() 9 return data 10 11 def parseDmi(data): 12 lines = [] 13 line_in = False 14 dmi_list = [i for i in data.split(‘\n‘) if i] 15 for line in dmi_list: 16 if line.startswith(‘System Information‘): 17 line_in = True 18 continue 19 if line_in: 20 if not line[0].strip(): 21 lines.append(line) 22 else: 23 break 24 return lines 25 26 def dimDic(): 27 dmi_dic = {} 28 data = getDmi() 29 lines = parseDmi(data) 30 dic = dict([i.strip().split(‘: ‘) for i in lines]) 31 dmi_dic[‘vendor‘] = dic[‘Manufacturer‘] 32 dmi_dic[‘product‘] = dic[‘Product Name‘] 33 dmi_dic[‘sn‘] = dic[‘Serial Number‘] 34 35 return dmi_dic 36 37 38 if __name__ == ‘__main__‘: 39 print dimDic()
时间: 2024-10-29 19:10:27