- 1 year ago
How to get all (non-disabled) user SIDs via Windows API?
Comment
1 / 1
To get all non-disabled user SIDs using the Windows API, you can use the NetUserEnum
function along with the USER_INFO_1
structure. Here's an example in C++:
cpp#include <windows.h>
#include <lm.h>
#include <iostream>
#include <vector>
#pragma comment(lib, "netapi32.lib")
int main() {
DWORD dwLevel = 1;
LPUSER_INFO_1 pUserInfo = NULL;
DWORD dwEntriesRead = 0;
DWORD dwTotalEntries = 0;
NET_API_STATUS nStatus;
// Enumerate user accounts
nStatus = NetUserEnum(NULL, dwLevel, FILTER_NORMAL_ACCOUNT, (LPBYTE*)&pUserInfo,
MAX_PREFERRED_LENGTH, &dwEntriesRead, &dwTotalEntries, NULL);
if (nStatus == NERR_Success) {
std::vector<std::wstring> userSids;
for (DWORD i = 0; i < dwEntriesRead; i++) {
// Check if the user account is not disabled
if ((pUserInfo[i].usri1_flags & UF_ACCOUNTDISABLE) == 0) {
// Add the user SID to the vector
userSids.push_back(pUserInfo[i].usri1_user_sid);
}
}
// Print the user SIDs
for (const auto& sid : userSids) {
std::wcout << sid << std::endl;
}
}
// Free the memory allocated by NetUserEnum
if (pUserInfo != NULL) {
NetApiBufferFree(pUserInfo);
}
return 0;
}
Make sure to link against the netapi32.lib
library. This example retrieves the user SIDs of all non-disabled user accounts using the NetUserEnum
function and filters out the disabled accounts based on the UF_ACCOUNTDISABLE
flag. The SIDs are stored in a vector and then printed to the console.
Note that you'll need appropriate privileges to run this code, such as being a member of the Administrators group.