Skip to content

Instantly share code, notes, and snippets.

@aug2uag
Last active August 9, 2020 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aug2uag/59bb3c9f9670219537680fa65e978e2c to your computer and use it in GitHub Desktop.
Save aug2uag/59bb3c9f9670219537680fa65e978e2c to your computer and use it in GitHub Desktop.
system monitoring
import psutil
# main function
def sysStats():
agg = {}
agg['posix_processes'] = _posixProcesses()
agg['windows_processes'] = _windowsProcesses()
agg['battery_info'] = _batteryInfo()
agg['cpu_info'] = _cpuInfo()
agg['mem_info'] = _memInfo()
agg['disk_info'] = _diskInfo()
return agg
def _posixProcesses():
acc = []
pids = psutil.pids()
for pid in pids:
# children and parents not guaranteed to return
# will fail if a processing closed midstream
o = {'pid': pid}
try:
p = psutil.Process(pid)
o['process'] = p.as_dict()
except Exception as e:
pass
try:
c = p.children(recursive=True)
o['children']= [_c.as_dict() for _c in c]
except Exception as e:
pass
try:
pp = p.parents()
o['parents'] = [_p.as_dict() for _p in pp]
except Exception:
pass
acc.append(o)
return acc
def _windowsProcesses():
acc = []
try:
s = list(psutil.win_service_iter())
for _s in s:
p = psutil.win_service_get(_s.name)
acc.append(p.as_dict())
except Exception:
pass
return acc
def _batteryInfo():
b = psutil.sensors_battery()
return {
'percent': b.percent,
'secsleft': b.secsleft,
'power_plugged': b.power_plugged
}
def _cpuInfo():
stat = psutil.cpu_stats()
freq = psutil.cpu_freq()
return {
'stats': {
'ctx_switches': stat.ctx_switches,
'interrupts': stat.interrupts,
'soft_interrupts': stat.soft_interrupts,
'syscalls': stat.syscalls
},
'frequency': {
'current': freq.current,
'min': freq.min,
'max': freq.max
},
'load_average': list(psutil.getloadavg()),
'count_logical': psutil.cpu_count(),
'count_no_logical': psutil.cpu_count(logical=False)
}
def _memInfo():
vmem = psutil.swap_memory()
smem = psutil.swap_memory()
return {
'virtual': {
'total': vmem.total,
'percent': vmem.percent,
'used': vmem.used,
'free': vmem.free,
},
'swap': {
'total': smem.total,
'used': smem.used,
'free': smem.free,
'percent': smem.percent,
'sin': smem.sin,
'sout': smem.sout
}
}
def _diskInfo():
agg = {}
partitions = []
_partitions = psutil.disk_partitions()
for p in _partitions:
partitions.append({
'device': p.device,
'mountpoint': p.mountpoint,
'fstype': p.fstype,
'opts': p.opts
})
agg['partitions'] = partitions
usage = psutil.disk_usage('/')
agg['usage'] = {
'total': usage.total,
'used': usage.used,
'free': usage.free,
'percent': usage.percent
}
io = psutil.disk_io_counters(perdisk=False)
agg['io'] = {
'read_count': io.read_count,
'write_count': io.write_count,
'read_bytes': io.read_bytes,
'write_bytes': io.write_bytes,
'read_time': io.read_time,
'write_time': io.write_time
}
return agg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment