forked from device42/nix_bsd_mac_inventory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
module_linux.py
465 lines (428 loc) · 20 KB
/
module_linux.py
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
import ast
import math
# Import Fabric API
from fabric.api import *
class GetLinuxData():
def __init__(self, GET_SERIAL_INFO, ADD_HDD_AS_DEVICE_PROPERTIES, ADD_HDD_AS_PARTS,
GET_HARDWARE_INFO, GET_OS_DETAILS,GET_CPU_INFO, GET_MEMORY_INFO,
IGNORE_DOMAIN, UPLOAD_IPV6, GIVE_HOSTNAME_PRECEDENCE,DEBUG):
self.GET_SERIAL_INFO = GET_SERIAL_INFO
self.GET_HARDWARE_INFO = GET_HARDWARE_INFO
self.GET_OS_DETAILS = GET_OS_DETAILS
self.GET_CPU_INFO = GET_CPU_INFO
self.GET_MEMORY_INFO = GET_MEMORY_INFO
self.IGNORE_DOMAIN = IGNORE_DOMAIN
self.UPLOAD_IPV6 = UPLOAD_IPV6
self.NAME_PRECEDENCE = GIVE_HOSTNAME_PRECEDENCE
self.ADD_HDD_AS_DEVP = ADD_HDD_AS_DEVICE_PROPERTIES
self.ADD_HDD_AS_PARTS = ADD_HDD_AS_PARTS
self.DEBUG = DEBUG
self.root = True
self.devicename = None
self.disk_sizes = {}
self.raids = {}
self.hdd_parts = {}
self.allData = []
self.devargs = {}
def main(self):
self.are_u_root()
self.get_system()
if self.GET_MEMORY_INFO:
self.get_ram()
if self.GET_CPU_INFO:
self.get_cpu()
if self.GET_OS_DETAILS:
self.get_os()
self.get_hdd()
self.get_IP()
self.allData.append(self.devargs)
if self.ADD_HDD_AS_PARTS:
self.allData.append({'hdd_parts':self.hdd_parts})
return self.allData
def execute(self, cmd, needroot = False):
if needroot and self.root == False:
if self.DEBUG:
print '[-] DEBUG: sudo(%s)' % cmd
output = sudo(cmd, combine_stderr=False, shell=False)
else:
if self.DEBUG:
print '[-] DEBUG: run(%s)' % cmd
output = run(cmd, combine_stderr=False)
data_err = output.stderr
data_out = output.stdout
# some OSes do not have sudo by default! We can try some of the commands without it (cat /proc/meminfo....)
if data_err and 'sudo: command not found' in str(data_err):
output = run(cmd, combin_stderr=False)
if self.DEBUG:
print '[-] DEBUG: run(%s)' % cmd
data_err = output.stderr
data_out = output.stdout
return data_out.splitlines(),data_err.splitlines()
def are_u_root(self):
cmd = 'id -u'
data, err = self.execute(cmd)
if data[0].strip() == '0':
self.root = True
else:
self.root = False
def to_ascii(self, s):
try:
return s.encode('ascii','ignore')
except:
return None
def closest_memory_assumption(self, v):
if v < 512: v = 128 * math.ceil(v / 128.0)
elif v < 1024: v = 256 * math.ceil(v / 256.0)
elif v < 4096: v = 512 * math.ceil(v / 512.0)
elif v < 8192: v = 1024 * math.ceil(v / 1024.0)
else: v = 2048 * math.ceil(v / 2048.0)
return int(v)
def get_name(self):
cmd = '/bin/hostname'
data_out,data_err = self.execute(cmd)
device_name = None
if not data_err:
if self.IGNORE_DOMAIN:
device_name = self.to_ascii(data_out[0].rstrip()).split('.')[0]
else:
device_name = self.to_ascii(data_out[0].rstrip())
if device_name != '':
self.devargs.update({'name': device_name})
if self.NAME_PRECEDENCE:
self.devargs.update({'new_name':device_name})
return device_name
return device_name
def get_system(self):
self.device_name = self.get_name()
if self.device_name not in ('', None):
cmd = '/usr/sbin/dmidecode -t system'
data_out,data_err = self.execute(cmd, True)
if not data_err:
dev_type = None
for rec in data_out:
if rec.strip() not in ('\n',' ','', None):
rec = rec.strip()
if rec.startswith('Manufacturer:'):
manufacturer = rec.split(':')[1].strip()
self.devargs.update({'manufacturer': manufacturer})
if manufacturer in ['VMware, Inc.', 'Bochs', 'KVM', 'QEMU',
'Microsoft Corporation', 'Xen', 'innotek GmbH']:
dev_type = 'virtual'
self.devargs.update({ 'type' : dev_type})
if manufacturer == 'VMware, Inc.':
self.devargs.update({ 'virtual_subtype' : 'vmware' })
elif manufacturer == 'KVM':
self.devargs.update({ 'virtual_subtype' : 'kvm' })
elif manufacturer == 'Microsoft Corporation':
self.devargs.update({ 'virtual_subtype' : 'hyperv' })
elif manufacturer == 'Xen':
self.devargs.update({ 'virtual_subtype' : 'citrix' })
if rec.startswith('UUID:'):
uuid = rec.split(':')[1].strip()
self.devargs.update({ 'uuid' : uuid})
if rec.startswith('Serial Number:'):
serial = rec.split(':')[1].strip()
self.devargs.update({ 'serial_no' : serial})
if rec.startswith('Product Name:') and dev_type != 'virtual':
hardware = rec.split(':')[1].strip()
self.devargs.update({'hardware': hardware})
else:
if self.DEBUG:
print '\t[-] Failed to get sysdata from host: %s using dmidecode. Message was: %s' % \
(self.machine_name, str(data_err))
self.get_system_2()
def get_system_2(self):
cmd = "grep '' /sys/devices/virtual/dmi/id/*"
data_out,data_err = self.execute(cmd, True)
if data_out:
dev_type = 'physical'
for rec in data_out:
if 'sys_vendor:' in rec:
manufacturer = rec.split(':')[1].strip()
self.devargs.update({'manufacturer': manufacturer})
if manufacturer in ['VMware, Inc.', 'Bochs', 'KVM', 'QEMU',
'Microsoft Corporation', 'Xen', 'innotek GmbH']:
dev_type = 'virtual'
self.devargs.update({ 'type' : dev_type})
if 'product_uuid:' in rec:
uuid = rec.split(':')[1].strip()
self.devargs.update({ 'uuid' : uuid})
if 'product_serial:' in rec:
serial = rec.split(':')[1].strip()
self.devargs.update({ 'serial_no' : serial})
if 'product_name:' in rec and dev_type != 'virtual':
hardware = rec.split(':')[1].strip()
self.devargs.update({'hardware': hardware})
else:
if self.DEBUG:
print '\t[-] Failed to get sysdata from host: %s using grep /sys.... Message was: %s' % \
(self.machine_name, str(data_err))
self.get_system_3()
def get_system_3(self):
cmd = "lshal -l -u computer"
data_out,data_err = self.execute(cmd)
if data_out:
dev_type = None
for rec in data_out:
if 'system.hardware.vendor' in rec:
manufacturer = rec.split('=')[1].split('(')[0].strip()
self.devargs.update({'manufacturer': manufacturer})
if manufacturer in ['VMware, Inc.', 'Bochs', 'KVM', 'QEMU',
'Microsoft Corporation', 'Xen', 'innotek GmbH']:
dev_type = 'virtual'
self.devargs.update({ 'type' : dev_type})
if 'system.hardware.uuid' in rec:
uuid = rec.split('=')[1].split('(')[0].strip()
self.devargs.update({ 'uuid' : uuid})
if 'system.hardware.serial' in rec:
serial = rec.split('=')[1].split('(')[0].strip()
self.devargs.update({ 'serial_no' : serial})
if 'system.hardware.product' in rec and dev_type != 'virtual':
hardware = rec.split('=')[1].split('(')[0].strip()
self.devargs.update({'hardware': hardware})
else:
if self.DEBUG:
print '\t[-] Failed to get sysdata from host: %s using lshal. Message was: %s' % \
(self.machine_name, str(data_err))
def get_ram(self):
cmd = 'grep MemTotal /proc/meminfo'
data_out, data_err = self.execute(cmd)
if not data_err:
memory_raw = ''.join(data_out).split()[1]
memory = self.closest_memory_assumption(int(memory_raw)/1024)
self.devargs.update({'memory': memory})
else:
if self.DEBUG:
print '\t[-] Could not get RAM info from host %s. Message was: %s' % (self.machine_name, str(data_err))
def get_os(self):
cmd = 'python -c "import platform; raw = list(platform.dist());raw.append(platform.release());print raw"'
data_out, data_err = self.execute(cmd)
if not data_err:
if not 'command not found' in data_out[0]: # because some distros sport python3 by default!
self.os,ver,release,kernel_version = ast.literal_eval(data_out[0])
self.devargs.update({'os': self.os})
self.devargs.update({'osver': ver})
self.devargs.update({'osverno': kernel_version})
else:
cmd = 'python3 -c "import platform; raw = list(platform.dist());raw.append(platform.release());print (raw)"'
data_out, data_err = self.execute(cmd)
if not data_err:
self.os,ver,release,kernel_version = ast.literal_eval(data_out[0])
self.devargs.update({'os': self.os})
self.devargs.update({'osver': ver})
self.devargs.update({'osverno': kernel_version})
else:
if self.DEBUG:
print '\t[-] Could not get OS info from host %s. Message was: %s' % (self.machine_name, str(data_err))
else:
if self.DEBUG:
print '\t[-] Could not get OS info from host %s. Message was: %s' % (self.machine_name, str(data_err))
def get_cpu(self):
cmd = 'cat /proc/cpuinfo'
data_out,data_err = self.execute(cmd)
if not data_err:
cpus = 0
cores = 1
siblings = None
cpuspeed = 0
for rec in data_out:
if rec.startswith('processor'):
cpus += 1
if rec.startswith('cpu MHz'):
cpuspeed = int((float(rec.split(':')[1].strip())))
if rec.startswith('cpu cores'):
cores = int(rec.split(':')[1].strip())
if rec.startswith('siblings'):
threads = int(rec.split(':')[1].strip())
if siblings:
processors = cpus / threads
else:
processors = cpus
self.devargs.update({'cpucount': processors})
self.devargs.update({'cpucore': cores})
self.devargs.update({'cpupower': cpuspeed})
else:
if self.DEBUG:
print '\t[-] Could not get CPU info from host %s. Message was: %s' % (self.machine_name, str(data_err))
def get_IP(self):
cmd = '/sbin/ifconfig'
data_out,data_err = self.execute(cmd)
if not data_err:
NEW = True
nic = mac = ip = ip6 = ''
for row in data_out:
if row not in ('','\n',None):
if not row.startswith(' '):
if NEW:
nic = row.split()[0].strip(':').strip()
NEW = False
else:
if not nic.startswith('lo'):
self.ip_to_json(nic,mac,ip,ip6)
nic = mac = ip = ip6 = ''
nic = row.split()[0].strip(':')
NEW = True
if 'HWaddr ' in row:
words = row.split()
macindex = words.index('HWaddr') + 1
mac = words[macindex].strip()
else:
NEW = False
if 'inet addr:' in row:
words = row.split()
ipindex = words.index('inet') + 1
ip = words[ipindex].strip('addr:').strip()
elif 'inet ' in row and 'addr:' not in row:
words = row.split()
ipindex = words.index('inet') + 1
ip = words[ipindex].strip()
if 'inet6 addr:' in row:
ip6 = row.split()[2]
if '%' in ip6:
ip6 = ip6.split('%')[0]
if '/' in ip6:
ip6 = ip6.split('/')[0]
elif 'inet6 ' in row and 'addr:' not in row:
ip6 = row.split()[1]
if '%' in ip6:
ip6 = ip6.split('%')[0]
if '/' in ip6:
ip6 = ip6.split('/')[0]
if 'ether ' in row:
words = row.split()
macindex = words.index('ether') + 1
mac = words[macindex].strip()
if not nic.startswith('lo'):
self.ip_to_json(nic,mac,ip,ip6)
else:
if self.DEBUG:
print '\t[-] Could not get IP info from host %s. Message was: %s' % (self.machine_name, str(data_err))
def ip_to_json(self, nic,mac,ip,ip6):
macData = {}
nicData = {}
nicData_v6 = {}
nicData.update({'device': self.device_name})
nicData_v6.update({'device': self.device_name})
macData.update({'device': self.device_name})
nicData.update({'tag':nic})
nicData_v6.update({'tag':nic})
macData.update({'port_name':nic})
nicData.update({'macaddress':mac})
nicData_v6.update({'macaddress':mac})
macData.update({'macaddress':mac})
nicData.update({'ipaddress':ip})
nicData_v6.update({'ipaddress':ip6})
#if ip != '':
self.allData.append(nicData)
if ip6 != '':
self.allData.append(nicData_v6)
if mac != '':
self.allData.append(macData)
def get_hdd(self):
# get software raids. Hardware raids are way too complicated to fetch automatically.
self.get_sw_raids()
# ==================
hdds = self.get_hdd_names()
if hdds:
if self.ADD_HDD_AS_DEVP:
self.devargs.update({'hddcount':len(hdds)})
for hdd in hdds:
self.get_hdd_info(hdd)
def get_hdd_names(self):
hdd_names = []
cmd = '/sbin/fdisk -l | grep "Disk /dev/[sh]da"'
data_out,data_err = self.execute(cmd, True)
errhdds = []
if data_err:
for rec in data_err:
if "doesn't contain a valid partition table" in rec:
disk = rec.split()[1]
errhdds.append(disk)
for rec in data_out:
try:
mess = rec.strip().split()
disk = mess[1]
if disk.endswith(':'):
disk_name = disk.strip(':')
else:
disk_name = disk
sizeformat = mess[3].lower().strip(',')
size = float(mess[2])
if self.ADD_HDD_AS_DEVP:
self.devargs.update({'hddsize':size})
if sizeformat in ('mib','mb'):
size = int(math.ceil(size /1024))
if self.ADD_HDD_AS_DEVP:
self.devargs.update({'hddsize':size})
hdd_names.append(disk_name)
self.disk_sizes.update({disk_name:size})
except Exception, e:
print e
pass
return hdd_names
def get_hdd_info(self, hdd):
success = self.get_hdd_info_hdaparm(hdd)
def get_hdd_info_hdaparm(self,hdd):
#if hdd not in self.raids:
cmd = 'hdparm -I %s' % hdd
data_out,data_err = self.execute(cmd, True)
if data_err:
if self.DEBUG:
print '[-] ERROR: %s' % data_err
return
else:
for rec in data_out:
if 'model number' in rec.lower():
model = rec.split(':')[1].strip()
size = self.disk_sizes[hdd]
self.hdd_parts.update({'device':self.device_name})
self.hdd_parts.update({'name':model})
self.hdd_parts.update({'type':'hdd'})
self.hdd_parts.update({'hddsize':size})
if 'serial number' in rec.lower():
serial = rec.split(':')[1].strip()
self.hdd_parts.update({'serial_no':serial})
if 'rotation rate' in rec.lower():
rpm = rec.split(':')[1].strip()
self.hdd_parts.update({'hddrpm':rpm})
if 'transport:' in rec.lower():
transport = 'unknown'
if ',' in rec:
try:
transport = (rec.split(',')[-1]).split()[0]
except:
transport = (rec.split(',')[-1])
else:
transport = rec.lower()
self.hdd_parts.update({'hddtype':transport})
def get_sw_raids(self):
cmd = 'cat /proc/mdstat'
# Note: we can get raid members here if needed!
data_out,data_err = self.execute(cmd, False)
if not data_err:
for rec in data_out:
if "active raid" in rec:
hddraid = 'software'
raw = rec.split()
for entry in raw:
if 'raid' in entry:
rtype = entry.strip()
hddraid_type = self.raid_type(rtype)
if self.ADD_HDD_AS_DEVP:
self.devargs.update({'hddraid':hddraid})
self.devargs.update({'hddraid_type':hddraid_type})
if self.ADD_HDD_AS_PARTS:
self.hdd_parts.update({'raid_type':hddraid_type})
def raid_type(self, rtype):
types = {'raido':'raid 0',
'raid1':'raid 1',
'raid3':'raid 3',
'raid4':'raid 4',
'raid5':'raid 5',
'raid6':'raid 6',
'raid10':'raid 10',
'raid50':'raid 50'}
if rtype in types:
return types[rtype]
else:
return rtype