【API】NetUserEnum-获取系统所有账户名称

1 说明

该NetUserEnum函数检索服务器上所有用户帐户的信息。

函数原型:

NET_API_STATUS NetUserEnum(
  _In_    LPCWSTR servername,
  _In_    DWORD   level,
  _In_    DWORD   filter,
  _Out_   LPBYTE  *bufptr,
  _In_    DWORD   prefmaxlen,
  _Out_   LPDWORD entriesread,
  _Out_   LPDWORD totalentries,
  _Inout_ LPDWORD resume_handle
);

参数说明

servername [in]

指向常量字符串的指针,该字符串指定要在其上执行函数的远程服务器的DNS或NetBIOS名称。如果此参数为NULL,则使用本地计算机。

level[in]

指定数据的信息级别。

filter [in]

指定要包含在枚举中的用户帐户类型的值。值为零表示应该包括所有正常用户,信任数据和机器账户数据。

bufptr [out]

接收数据的指针。

prefmaxlen [in]

返回数据的首选最大长度(以字节为单位)。如果指定MAX_PREFERRED_LENGTH,则NetUserEnum函数会分配数据所需的内存量。如果在此参数中指定另一个值,则可以限制该函数返回的字节数。如果缓冲区大小不足以保存所有条目,则函数返回ERROR_MORE_DATA。

entriesread [out]

指向一个值的指针,它接收实际枚举的元素的数量。

totalentries [out]

指向一个值的指针,该值接收可能已从当前继续位置枚举的条目总数。

resume_handle [in, out]

指向包含用于继续现有用户搜索的恢复句柄的值的指针。

返回值

如果函数成功,返回值是NERR_Success。

2 代码

void CMy20180203_MFC_获取系统所有账户名称Dlg::OnBnClickedGetalluser()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData(TRUE);

	LPUSER_INFO_0 pBuf = NULL;
	LPUSER_INFO_0 pTmpBuf;
	DWORD dwLevel = 0;
	DWORD dwPrefMaxLen = MAX_PREFERRED_LENGTH;
	DWORD dwEntriesRead = 0;
	DWORD dwTotalEntries = 0;
	DWORD dwResumeHandle = 0;
	DWORD i;
	DWORD dwTotalCount = 0;
	NET_API_STATUS nStatus;
	LPTSTR pszServerName = NULL;

	do // begin do
	{
		nStatus = NetUserEnum(NULL,
			dwLevel,
			FILTER_NORMAL_ACCOUNT, // global users
			(LPBYTE*)&pBuf,
			dwPrefMaxLen,
			&dwEntriesRead,
			&dwTotalEntries,
			&dwResumeHandle);
		//
		// If the call succeeds,
		//
		if ((nStatus == NERR_Success) || (nStatus == ERROR_MORE_DATA))
		{
			if ((pTmpBuf = pBuf) != NULL)
			{
				//
				// Loop through the entries.
				//
				for (i = 0; (i < dwEntriesRead); i++)
				{
					assert(pTmpBuf != NULL);

					if (pTmpBuf == NULL)
					{
						m_username.Format(_T("%s"), "An access violation has occurred
");
						break;
					}
					//
					//  Print the name of the user account.
					//

					TCHAR tcBuffer[1024] = { 0 };
					wsprintf(tcBuffer, L"	-- %s
", pTmpBuf->usri0_name);
					m_username += tcBuffer;

					pTmpBuf++;
					dwTotalCount++;
				}
			}
		}
		//
		// Otherwise, print the system error.
		//
		else
			fprintf(stderr, "A system error has occurred: %d
", nStatus);
		//
		// Free the allocated buffer.
		//
		if (pBuf != NULL)
		{
			NetApiBufferFree(pBuf);
			pBuf = NULL;
		}
	}
	// Continue to call NetUserEnum while 
	//  there are more entries. 
	// 
	while (nStatus == ERROR_MORE_DATA); // end do
										//
										// Check again for allocated memory.
										//
	if (pBuf != NULL)
		NetApiBufferFree(pBuf);
	//
	// Print the final count of users enumerated.
	//
	m_CountNum.Format(L"总计有%d个账户被枚举", dwTotalCount);
	
	UpdateData(FALSE);
}

3 界面

4 参考

  • MFC中EDIT控件实现换行

http://blog.csdn.net/dearwind153/article/details/50241537

  • NetUserEnum function

https://msdn.microsoft.com/en-us/library/windows/desktop/aa370652(v=vs.85).aspx

原文地址:https://www.cnblogs.com/17bdw/p/8410571.html