/
sysinfo.py
397 lines (355 loc) · 10.8 KB
/
sysinfo.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
import psutil
import platform
import socket
import datetime
import json
def main():
data = {
'system_info': get_dict_system_info(),
'cpu_usage': get_dict_cpu_usage(0.1,True),
'cpu_count': get_dict_cpu_count(),
'mem_usage': get_dict_mem_usage(),
'swap_usage': get_dict_smem_usage(),
'disks': get_dict_disks(),
'io_counters': get_dict_io_counters(True),
'net_counters': get_dict_net_counters(True),
'net_connections': get_dict_net_connections(),
'current_users': get_dict_current_users(),
'boot_time': get_dict_boot_time(),
'processes': get_dict_processes()
}
#print(json.dumps(data, sort_keys=True, indent=4))
print(json.dumps(data))
def show_all():
# show_system_info()
# show_cpu_usage(0.5)
# show_cpu_count()
# show_mem_usage()
# show_smem_usage()
# show_disks()
# show_io_counters(True)
# show_net_counters(True)
# show_net_connections()
# show_current_users()
# show_boot()
# show_processes()
pass
def show_boot():
boot = psutil.boot_time()
print("Last boot:", get_date_string(boot))
def show_disks():
disks = psutil.disk_partitions(all=True)
for disk in disks:
print("dev:", disk.device)
print("\tmount:", disk.mountpoint)
print("\tfstype:", disk.fstype)
print("\toptions:", disk.opts)
def show_cpu_usage(given_interval, separate=False):
usage = psutil.cpu_percent(interval=given_interval, percpu=separate)
if separate:
for i in range(len(usage)):
print("Core", i, "usage", usage[i])
else:
print("Total cpu usage:", usage)
def show_processes(running_as_root=False):
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict()
except psutil.NoSuchProcess:
pass
else:
print("Process name:", pinfo['name'])
print("\tCreation time:", get_date_string(pinfo['create_time']))
print("\tOpen files:", pinfo['open_files'])
print("\tIO counter:", pinfo['io_counters'])
print("\tCPU times:", pinfo['cpu_times'])
print("\tThreads num:", pinfo['num_threads'])
print("\tMemory usage:", pinfo['memory_percent'], "%")
print("\tContext switches:", pinfo['num_ctx_switches'])
print("\tWorking directory:", pinfo['cwd'])
print("\tParent pid:", pinfo['ppid'])
print("\tThreads:", pinfo['threads'])
print("\tStatus:", pinfo['status'])
print("\tExecutable:", pinfo['exe'])
print("\tPriority:", pinfo['nice'])
# TODO: FIX SO THAT THIS WILL BE CHECKED ONLY ON WINDOWS
try:
print("\tHandles:", pinfo['num_handles'])
except:
pass
print("\tUsername:", pinfo['username'])
print("\tCpu_affinity", pinfo['cpu_affinity'])
print("\tPID:", pinfo['pid'])
print("\tCPU usage:", pinfo['cpu_percent'], "%")
print("\tIO priority:", pinfo['ionice'])
print("\tMem info", pinfo['memory_info_ex'])
print("\tCommand:", pinfo['cmdline'])
print("\tMemory maps:", pinfo['memory_maps'])
print("\tConnections:")
show_net_connection_from_array(pinfo['connections'])
def show_cpu_count():
count_hard = psutil.cpu_count(logical=False)
count_logi = psutil.cpu_count(logical=True)
print("CPU found (logical/physical):", count_logi, "/", count_hard)
def show_mem_usage():
mem = psutil.virtual_memory()
print("Mem total:\t", round((mem.total/1024)/1024,2), "MB")
print("Mem free:\t", round((mem.available/1024)/1024, 2), "MB")
print("Mem used:\t", mem.percent,"%")
def show_smem_usage():
smem = psutil.swap_memory()
print("Swap total:\t", round((smem.total/1024)/1024,2), "MB")
print("Swap free:\t", round((smem.free/1024)/1024, 2), "MB")
print("Swap used:\t", smem.percent,"%")
def show_io_counters(separate=False):
disks = psutil.disk_io_counters(perdisk=separate)
for disk in disks.keys():
data = disks[disk]
print("Drive:", disk)
print(" Read count:\t", data.read_count)
print(" \t bytes:\t\t", data.read_bytes)
print(" \t time:\t\t", data.read_time)
print(" Write count:\t", data.write_count)
print(" \t bytes:\t\t", data.write_bytes)
print(" \t time:\t\t", data.write_time)
def show_system_info():
uname = platform.uname()
print("Hostname: ", uname.node)
print("System family: ", uname.system)
print("System release: ", uname.release)
print("System version: ", uname.version)
print("Instruction set:", uname.machine)
def show_net_counters(separate=False):
cons = psutil.net_io_counters(pernic=True)
for con in cons.keys():
data = cons[con]
print("Connection:", con)
print("Bytes sent:", data.bytes_sent)
print("Bytes recv:", data.bytes_recv)
print("Packets sent:", data.packets_sent)
print("Packets recv:", data.packets_recv)
print("Err in/out/dropin/dropout:", data.errin, data.errout, data.dropin, data.dropout)
def show_current_users():
users = psutil.users()
for user in users:
print("User name:", user.name)
print("User terminal:", user.terminal)
print("Logged from host:", user.host)
print("Logged on since:", get_date_string(user.started))
def get_dict_system_info():
uname = platform.uname()
return {
'family': uname.system,
'hostname': uname.node,
'release': uname.release,
'version': uname.version,
'i_set': uname.machine
}
def show_net_connections(mykind='all'):
""" Acceptable values are: inet, inet4, inet6, tcp, tcp4, tcp6, udp, udp4, udp6, unix, all """
cons = psutil.net_connections(kind=mykind)
for con in cons:
print("Local address:", con.laddr)
print("\tRemote address:", con.raddr)
if con.family == socket.AF_INET:
print("\tFamily: AF_INET")
elif con.family == socket.AF_INET6:
print("\tFamily: AF_INET6")
else:
print("\tFamily: UNKNWN")
if con.type == socket.SOCK_STREAM:
print("\tType: SOCK_STREAM")
elif con.type == socket.SOCK_DGRAM:
print("\tType: SOCK_DGRAM")
print("\tStatus:", con.status)
print("\tPid:", con.pid)
def show_net_connection_from_array(arr):
cons = arr
for con in cons:
print("\t\tLocal address:", con.laddr)
print("\t\tRemote address:", con.raddr)
if con.family == socket.AF_INET:
print("\t\tFamily: AF_INET")
elif con.family == socket.AF_INET6:
print("\t\tFamily: AF_INET6")
else:
print("\t\tFamily: UNKNWN")
if con.type == socket.SOCK_STREAM:
print("\t\tType: SOCK_STREAM")
elif con.type == socket.SOCK_DGRAM:
print("\t\tType: SOCK_DGRAM")
print("\t\tStatus:", con.status)
def get_dict_disks():
disks = psutil.disk_partitions(all=True)
result = []
for disk in disks:
ele = {
'device': disk.device,
'mount': disk.mountpoint,
'fstype': disk.fstype,
'options': disk.fstype
}
result.append(ele)
return result
def get_date_string(date):
return datetime.datetime.utcfromtimestamp(
int(date)
).strftime('%Y-%m-%d %H:%M:%S')
def get_dict_boot_time():
return {'boot': psutil.boot_time()}
def get_dict_processes(running_as_root=False):
result = []
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict()
except psutil.NoSuchProcess:
pass
else:
ele = {
'name': pinfo['name'],
'creation_time': pinfo['create_time'],
'open_files': pinfo['open_files'],
'io_counter': pinfo['io_counters'],
'cpu_times': pinfo['cpu_times'],
'threads_num': pinfo['num_threads'],
'mem_usage': pinfo['memory_percent'],
'context_switches': pinfo['num_ctx_switches'],
'working_directory': pinfo['cwd'],
'parent_pid': pinfo['ppid'],
'threads': pinfo['threads'],
'status': pinfo['status'],
'executable': pinfo['exe'],
'priority': pinfo['nice'],
'username': pinfo['username'],
'cpu_affinity': pinfo['cpu_affinity'],
'pid': pinfo['pid'],
'cpu_usage': pinfo['cpu_percent'],
'io_priority': pinfo['ionice'],
'mem_info': pinfo['memory_maps'],
'connections': get_dict_net_connection_from_array(pinfo['connections'])
}
uname = platform.uname()
if uname.system == "Windows":
ele.update({'handles':pinfo['num_handles']})
result.append(ele)
return result
def get_dict_cpu_usage(given_interval, separate=False):
usage = psutil.cpu_percent(interval=given_interval, percpu=separate)
usage_list = []
if separate:
for i in range(len(usage)):
usage_list.append(usage[i])
else:
usage_list.append(usage)
return usage_list
def get_dict_cpu_count():
return { 'physical': psutil.cpu_count(logical=False), 'logical': psutil.cpu_count(logical=True) }
def get_dict_mem_usage():
mem = psutil.virtual_memory()
return {
'total': mem.total,
'free': mem.available,
'used_percent': mem.percent
}
def get_dict_smem_usage():
smem = psutil.swap_memory()
return {
'total': smem.total,
'free': smem.free,
'used': smem.percent
}
def get_dict_io_counters(separate=False):
disks = psutil.disk_io_counters(perdisk=separate)
result = []
for disk in disks.keys():
data = disks[disk]
ele = {
'disk': disk,
'r_count': data.read_count,
'r_bytes': data.read_bytes,
'r_time': data.read_time,
'w_count': data.write_count,
'w_bytes': data.write_bytes,
'w_time': data.write_time,
}
result.append(ele)
return result
def get_dict_net_counters(separate=False):
cons = psutil.net_io_counters(pernic=True)
result = []
for con in cons.keys():
data = cons[con]
ele = {
'nic': con,
'bytes_sent': data.bytes_sent,
'bytes_recv': data.bytes_recv,
'packets_sent': data.packets_sent,
'packets_recv': data.packets_recv,
'err_in': data.errin,
'err_out': data.errout,
'drop_in': data.dropin,
'drop_out': data.dropout
}
result.append(ele)
return result
def get_dict_current_users():
results = []
users = psutil.users()
for user in users:
ele = {
'name': user.name,
'terminal': user.terminal,
'host': user.host,
'logon_time': user.started
}
results.append(ele)
return results
def get_dict_net_connections(mykind='all'):
cons = psutil.net_connections(kind=mykind)
result = []
for con in cons:
ele = {
'local_address': con.laddr,
'remote_address': con.raddr,
'status': con.status,
'pid': con.pid
}
if con.family == socket.AF_INET:
ele.update({'family':'AF_INET'})
elif con.family == socket.AF_INET6:
ele.update({'family':'AF_INET6'})
else:
ele.update({'family':'UNKNWN'})
if con.type == socket.SOCK_STREAM:
ele.update({'type':'STREAM'})
elif con.type == socket.SOCK_DGRAM:
ele.update({'type':'DATAGRAM'})
else:
ele.update({'type':'UNKNWN'})
result.append(ele)
return result
def get_dict_net_connection_from_array(arr):
cons = arr
result = []
for con in cons:
ele = {
'local_address': con.laddr,
'remote_address': con.raddr,
'status': con.status,
}
if con.family == socket.AF_INET:
ele.update({'family':'AF_INET'})
elif con.family == socket.AF_INET6:
ele.update({'family':'AF_INET6'})
else:
ele.update({'family':'UNKNWN'})
if con.type == socket.SOCK_STREAM:
ele.update({'type':'STREAM'})
elif con.type == socket.SOCK_DGRAM:
ele.update({'type':'DATAGRAM'})
else:
ele.update({'type':'UNKNWN'})
result.append(ele)
return result
if __name__ == "__main__":
main()