Enumerating Processes with WTSEnumerateProcesses

This is a quick and dirty example using WTSEnumerateProcess to enumerate processes on a Windows host. This function is part of the Windows Terminal Services API.

WTSEnumerateProcess populates a WTS_PROCESS_INFO structure with information pertaining to running processes on the specified host. If the hServer parameter is set to WTS_CURRENT_SERVER_HANDLE, this will run against the host which is running the software.

#include <iostream>
#include <Windows.h>
#include <WtsApi32.h>
#include <sddl.h>

#pragma comment(lib, "Wtsapi32.lib")


int main() {
    WTS_PROCESS_INFO *processes = NULL;
    LPTSTR sid;
    DWORD count = 0;

    if (WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, NULL, 1, &processes, &count)) {
        for (DWORD i = 0; i < count; i++) {
            if (!ConvertSidToStringSid(processes[i].pUserSid, &sid)) {
                std::wcout <<
                    processes[i].pProcessName <<
                    " " <<
                    processes[i].ProcessId <<
                    " " <<
                    processes[i].SessionId <<
                    " " <<
                    std::endl;
            } else {
                std::wcout <<
                    processes[i].pProcessName <<
                    " " <<
                    processes[i].ProcessId <<
                    " " <<
                    processes[i].SessionId <<
                    " " <<
                    sid <<
                    " " <<
                    std::endl;
            }
        }
    } else {
        return GetLastError();
    }

    WTSFreeMemory(processes);

    return NO_ERROR;
}


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s