Aden McCusker
Aden McCusker

Reputation: 3

Get Username/SID of the Owner of a process - Powershell/Python

I'm looking to get JUST the username of the owner of a process, not in a list, array or table. I need it completely by itself so when I store the output in a variable, it is ONLY the username. (An SID instead of a username will also suffice) This has to work in Powershell 2.0 or Python 2.*. I'm still fairly new to both powershell and python so working examples are greatly appreciated, and if it helps, explorer.exe is the process I want to find the username of the owner for. Also, I need to run the command/script provided as an answer under the SYSTEM context.(You can provide your answer either completely in python or completely in powershell, it does not matter for what I am doing)

P.S. Windows Only :D

Upvotes: 0

Views: 4268

Answers (2)

Simon Catlin
Simon Catlin

Reputation: 2229

Answer accepted above, I know, but for future reference:

Get-WmiObject -Class Win32_Process -Filter 'Name = "explorer.exe"' | ForEach-Object { $_.GetOwner() }

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168886

Python's psutil seems like a good choice for this:

import psutil

pid = 1
username = psutil.Process(pid).username

print "Process {} is owned by {}".format(pid, username)

On Linux the result is:

Process 1 is owned by root

Upvotes: 3

Related Questions