Skip to content

Instantly share code, notes, and snippets.

@DD-ScottBeamish
Last active February 9, 2021 21:59
Show Gist options
  • Save DD-ScottBeamish/0dd774fc8917c06c02f55a10722ff56e to your computer and use it in GitHub Desktop.
Save DD-ScottBeamish/0dd774fc8917c06c02f55a10722ff56e to your computer and use it in GitHub Desktop.
Windows - Get process CPU, Private Memory, and Virtual Memory for each user
from checks import AgentCheck
from datadog_checks.utils.subprocess_output import get_subprocess_output
class GetProcessByUser(AgentCheck):
def check(self, instance):
processes, err, retcode = get_subprocess_output(["powershell.exe", "Get-Process -IncludeUserName | where {$_.Username -notlike \"*NT AUTHORITY*\"} | where {$_.Username -notlike \"*SYSTEM*\"} | where {$_.Username -ne $null} | where {$_.Username -notlike \"*Window Manager*\"} | Select ProcessName,Username,CPU,PM,VM"], self.log, raise_on_empty_output=True)
# ProcessName : Code
# UserName : WIN-5OU1M45KDAQ\vagrant
# CPU : 14.28125
# PM : 114016256
# VM : 379031552
# Read each line and split by tab to get individual values
#
# Handles: The number of handles that the process has opened.
# NPM(K): The amount of non-paged memory that the process is using, in kilobytes.
# PM(K): The amount of pageable memory that the process is using, in kilobytes.
# WS(K): The size of the working set of the process, in kilobytes. The working set consists of the pages of memory that were recently referenced by the process.
# VM(M): The amount of virtual memory that the process is using, in megabytes. Virtual memory includes storage in the paging files on disk.
# CPU(s): The amount of processor time that the process has used on all processors, in seconds.
# ID: The process ID (PID) of the process.
# ProcessName: The name of the process.
for process in processes.split('\r\n'):
if process:
kvp = process.split(':')
if kvp[0].rstrip()== "ProcessName":
p = "ProcessName:" + kvp[1].lstrip()
elif kvp[0].rstrip() == "UserName":
u = "UserName:" + kvp[1].lstrip()
elif kvp[0].rstrip() == "CPU":
cpu = float(kvp[1].lstrip())
self.gauge("process.cpu",cpu,tags=[p,u])
elif kvp[0].rstrip() == "PM":
pm = int(kvp[1].lstrip())
self.gauge("process.pm",pm,tags=[p,u])
elif kvp[0].rstrip() == "VM":
vm = int(kvp[1].lstrip())
self.gauge("process.vm",vm,tags=[p,u])
@DD-ScottBeamish
Copy link
Author

DD-ScottBeamish commented Dec 27, 2018

Custom Agent Check for Windows that will pull all processes by username

  1. Copy GetUserProcess.py -> %ProgramData%\Datadog\checks.d\GetProcessByUser.py

  2. Copy GetUserProcess.yaml -> %ProgramData%\Datadog\conf.d\GetProcessByUser.d\GetProcessByUser.yaml

  3. Restart the Agent using Powershell.
    & "C:\Program Files\Datadog\Datadog Agent\embedded\agent.exe" restart-service

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment