forked from nima/python-dmidecode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdmidecode.py
More file actions
360 lines (306 loc) · 12.5 KB
/
dmidecode.py
File metadata and controls
360 lines (306 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#
# dmidecode.py
# Module front-end for the python-dmidecode module.
#
# Copyright 2009 David Sommerseth <davids@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# For the avoidance of doubt the "preferred form" of this code is one which
# is in an open unpatent encumbered format. Where cryptographic key signing
# forms part of the process of creating an executable the information
# including keys needed to generate an equivalently functional executable
# are deemed to be part of the source code.
#
try:
from lxml import etree
except ImportError:
raise ImportError("lxml is required. Install with: pip install lxml")
from dmidecodemod import *
from lxml import etree
from dmidecodemod import xmlapi
DMIXML_NODE = 'n'
DMIXML_DOC = 'd'
class dmidecodeXML:
"Native Python API for retrieving dmidecode information as XML"
def __init__(self):
self.restype = DMIXML_NODE
def SetResultType(self, type):
if type == DMIXML_NODE:
self.restype = DMIXML_NODE
elif type == DMIXML_DOC:
self.restype = DMIXML_DOC
else:
raise TypeError("Invalid result type value")
return True
def QuerySection(self, sectname):
try:
query_args = {
'query_type': 's',
'result_type': 'n' if self.restype == DMIXML_NODE else 'd',
'section': sectname
}
xml_string = xmlapi(**query_args)
if not xml_string or not isinstance(xml_string, str):
raise RuntimeError("C module did not return a valid XML string")
if self.restype == DMIXML_NODE:
return etree.fromstring(xml_string)
elif self.restype == DMIXML_DOC:
return etree.ElementTree(etree.fromstring(xml_string))
else:
raise TypeError("Invalid result type value")
except Exception as e:
raise RuntimeError(f"Failed to query section '{sectname}': {str(e)}")
def QueryTypeId(self, tpid):
try:
tpid = int(tpid)
query_args = {
'query_type': 't',
'result_type': 'n' if self.restype == DMIXML_NODE else 'd',
'typeid': tpid
}
xml_string = xmlapi(**query_args)
if not xml_string or not isinstance(xml_string, str):
raise RuntimeError("C module did not return a valid XML string")
if self.restype == DMIXML_NODE:
return etree.fromstring(xml_string)
elif self.restype == DMIXML_DOC:
return etree.ElementTree(etree.fromstring(xml_string))
else:
raise TypeError("Invalid result type value")
except Exception as e:
raise RuntimeError(f"Failed to query type ID '{tpid}': {str(e)}")
# Convenience functions for backward compatibility
def query_section(sectname, result_type=DMIXML_NODE):
"""
Convenience function to query a section and return lxml object
"""
dmi = dmidecodeXML()
dmi.SetResultType(result_type)
return dmi.QuerySection(sectname)
def query_type_id(tpid, result_type=DMIXML_NODE):
"""
Convenience function to query a type ID and return lxml object
"""
dmi = dmidecodeXML()
dmi.SetResultType(result_type)
return dmi.QueryTypeId(tpid)
# Backward compatibility class for older API
class DMIDecode:
def __init__(self):
self.dmi = dmidecodeXML()
def get(self, section=None, type_id=None):
try:
if section is not None:
section = str(section)
xml_data = self.dmi.QuerySection(section)
elif type_id is not None:
if isinstance(type_id, dict):
try:
type_id = int(list(type_id.keys())[0], 16)
except Exception as e:
raise ValueError(f"Invalid type_id dict format: {type_id}") from e
else:
type_id = int(type_id)
xml_data = self.dmi.QueryTypeId(type_id)
else:
raise ValueError("Either section or type_id must be specified")
if xml_data is None:
return {}
return self._xml_to_dict(xml_data)
except Exception as e:
import traceback
traceback.print_exc()
return {}
def _xml_to_dict(self, xml_element):
result = {}
if xml_element.attrib:
result.update(xml_element.attrib)
if xml_element.text and xml_element.text.strip():
if len(xml_element) == 0:
return xml_element.text.strip()
else:
result['_text'] = xml_element.text.strip()
for child in xml_element:
child_data = self._xml_to_dict(child)
if child.tag in result:
if not isinstance(result[child.tag], list):
result[child.tag] = [result[child.tag]]
result[child.tag].append(child_data)
else:
result[child.tag] = child_data
return result
def system(self):
"""Get system information"""
return self.get(section="system")
def bios(self):
"""Get BIOS information"""
return self.get(type_id=0)
def baseboard(self):
"""Get baseboard information"""
return self.get(type_id=2)
def chassis(self):
"""Get chassis information"""
return self.get(type_id=3)
def processor(self):
"""Get processor information"""
return self.get(type_id=4)
def memory(self):
"""Get memory information"""
return self.get(section="memory")
def model(self):
"""Get system model information"""
try:
system_info = self.get(section="system")
if system_info and isinstance(system_info, dict):
# Try to find model/product name in the system info
# Look for common keys that might contain model info
for key in ['product', 'model', 'product_name', 'system_product_name']:
if key in system_info:
return system_info[key]
# If it's nested, try to find it in nested structures
for value in system_info.values():
if isinstance(value, dict):
for subkey in ['product', 'model', 'product_name']:
if subkey in value:
return value[subkey]
return "Unknown"
except Exception as e:
print(f"Error getting model info: {e}")
return "Unknown"
def manufacturer(self):
"""Get system manufacturer"""
try:
system_info = self.get(section="system")
if system_info and isinstance(system_info, dict):
for key in ['manufacturer', 'vendor', 'system_manufacturer']:
if key in system_info:
return system_info[key]
# Check nested structures
for value in system_info.values():
if isinstance(value, dict):
for subkey in ['manufacturer', 'vendor']:
if subkey in value:
return value[subkey]
return "Unknown"
except Exception as e:
print(f"Error getting manufacturer info: {e}")
return "Unknown"
def version(self):
"""Get system version"""
try:
system_info = self.get(section="system")
if system_info and isinstance(system_info, dict):
for key in ['version', 'system_version']:
if key in system_info:
return system_info[key]
# Check nested structures
for value in system_info.values():
if isinstance(value, dict):
if 'version' in value:
return value['version']
return "Unknown"
except Exception as e:
print(f"Error getting version info: {e}")
return "Unknown"
def serial(self):
"""Get system serial number"""
try:
system_info = self.get(section="system")
if system_info and isinstance(system_info, dict):
for key in ['serial', 'serial_number', 'system_serial']:
if key in system_info:
return system_info[key]
# Check nested structures
for value in system_info.values():
if isinstance(value, dict):
for subkey in ['serial', 'serial_number']:
if subkey in value:
return value[subkey]
return "Unknown"
except Exception as e:
print(f"Error getting serial info: {e}")
return "Unknown"
def cpu_type(self):
"""Get CPU type/model information"""
try:
# Try processor section first
proc_info = self.get(type_id=4) # Type 4 is processor
if proc_info and isinstance(proc_info, dict):
# Look for CPU model/type info
for key in ['version', 'model', 'name', 'processor_version', 'processor_name']:
if key in proc_info:
return proc_info[key]
# Check nested structures
for value in proc_info.values():
if isinstance(value, dict):
for subkey in ['version', 'model', 'name']:
if subkey in value:
return value[subkey]
# If that fails, try a different approach
return "Unknown"
except Exception as e:
print(f"Error getting CPU type: {e}")
return "Unknown"
def cpu(self):
"""Alias for cpu_type() for compatibility"""
return self.cpu_type()
# Example usage functions
def get_system_info():
"""
Get system information as a convenient dictionary
"""
try:
root = query_section("system")
if root is None:
return None
system_info = {}
# Extract common system information
for elem in root.iter():
if elem.tag == "manufacturer":
system_info["manufacturer"] = elem.text
elif elem.tag == "product":
system_info["product"] = elem.text
elif elem.tag == "version":
system_info["version"] = elem.text
elif elem.tag == "serial":
system_info["serial"] = elem.text
elif elem.tag == "uuid":
system_info["uuid"] = elem.text
elif elem.tag == "family":
system_info["family"] = elem.text
return system_info
except Exception as e:
print(f"Error getting system info: {e}")
return None
def get_memory_info():
"""
Get memory information as a list of memory modules
"""
try:
root = query_section("memory")
if root is None:
return None
memory_modules = []
# This is a simplified example - you'd need to adjust based on actual XML structure
for device in root.findall(".//memory_device"):
module = {}
for child in device:
module[child.tag] = child.text
memory_modules.append(module)
return memory_modules
except Exception as e:
print(f"Error getting memory info: {e}")
return None