Shashwat Kumar
Shashwat Kumar

Reputation: 5297

Powershell alternative to Unix who command to show ssh sessions

I am on a windows server and want to know who has ssh-ed into the server. On Linux following command works

who -s

What is its alternative on Windows 10?

Upvotes: 3

Views: 6356

Answers (2)

stackprotector
stackprotector

Reputation: 13588

With an elevated PowerShell, you can list all logged on users with:

Get-CimInstance -ClassName Win32_LogonSession | Get-CimAssociatedInstance -Association Win32_LoggedOnUser

To only get the users that are logged on via SSH, you can use the following pipeline:

Get-CimInstance -ClassName Win32_Process -Filter "Name = 'sshd.exe'" | Get-CimAssociatedInstance -Association Win32_SessionProcess | Get-CimAssociatedInstance -Association Win32_LoggedOnUser | Where-Object {$_.Name -ne 'SYSTEM'}

Explanation:

You are looking for accounts that are logged on (via SSH). In WMI, accounts are represented by the Win32_Account class. Logon sessions are represented by the Win32_LogonSession class. If a user is logged on, a Win32_Account will be associated with a Win32_LogonSession. This association will be represented by an instance of the Win32_LoggedOnUser class.

The first pipeline from above takes all existing logon sessions and returns all user accounts that are associated with these logon sessions. In conclusion, you get a list of all logged on users.

To get a list of all users that are logged on via SSH, you can evaluate some more associations. Each process (Win32_Process) is associated with a logon session via the Win32_SessionProcess class. The second pipeline from above does the following:

  1. It filters all processes to only get the processes of the SSH daemon.
  2. For the SSH processes, it determines the associated logon sessions (Win32_LogonSession) via the Win32_SessionProcess association class.
  3. It then uses these logon sessions to determine the logged on users via the Win32_LoggedOnUser association class like in the first pipeline.
  4. In the end, it filters the result to omit the SYSTEM account.

Upvotes: 6

CFou
CFou

Reputation: 1190

You can get the owner of the sshd process :

Get-CimInstance Win32_Process -Filter "Name = 'sshd.exe'" | `
    Invoke-CimMethod -MethodName GetOwner | Where User -ne System

Then discard the System User which is used by the service itself, other users are the connected ones

Upvotes: 3

Related Questions