向事件添加用户名






4.40/5 (5投票s)
2006年2月22日

40767
如何将用户名添加到事件查看器。
引言
本文将解释如何将用户名添加到事件查看器中记录的事件中。
背景
我需要将用户名添加到正在记录的事件中,但没有找到直接相关的资料。微软网站上说只需将 SID 添加到 ReportEvent
函数中。但它没有说明如何获取 SID。经过大量调查,我找到一篇用另一种编程语言编写的文章,该文章获取了用户 SID,所以我将其翻译成 C 并与我正在做的事情结合起来。
使用代码
我首先编写了一个独立的程序来测试我想在工作中做的事情。我将提供所有相关部分,以便您可以简单地将可用的内容粘贴到您的项目中。
HANDLE hToken; HANDLE g_eventHandle = NULL; int rc; DWORD dwLength = 0; PTOKEN_USER pTokenUser = NULL; TCHAR *params[1]; // in order to use ReportEvent we must first Register Event g_eventHandle = RegisterEventSource(NULL, _T("SID_TEST")); OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken); // Get required buffer size and allocate the PTOKEN_USER buffer. if (!GetTokenInformation( hToken, // handle to the access token TokenUser, // get information about the token's groups (LPVOID) pTokenUser, // pointer to TOKEN_USER buffer 0, // size of buffer &dwLength // receives required buffer size )) { if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) goto Cleanup; pTokenUser = (PTOKEN_USER)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength); if (pTokenUser == NULL) goto Cleanup; } // Get the token group information from the access token. if (!GetTokenInformation( hToken, // handle to the access token TokenUser, // get information about the token's groups (LPVOID) pTokenUser, // pointer to TOKEN_USER buffer dwLength, // size of buffer &dwLength // receives required buffer size )) { goto Cleanup; } params[0] = const_cast<TCHAR*>("test string"); // the actual call that places the event into the Event Viewer rc = ReportEvent(g_eventHandle, EVENTLOG_INFORMATION_TYPE, 0, 0, pTokenUser->User.Sid,// the sid goes here <------- 1, 0, (LPCTSTR *)params, NULL); Cleanup: // Free the buffer for the token . if (pTokenUser != NULL) HeapFree(GetProcessHeap(), 0, (LPVOID)pTokenUser); // i am finished with the Event DeregisterEventSource(g_eventHandle);
关注点
就这样了。GetTokenInformation
函数需要调用两次;如果您为 SID 分配的内存过多或过少,该函数将失败。
带有我们条目的事件查看器