访问远程计算机
可以使用 Windows 事件日志 API 访问本地计算机或远程计算机上的数据。 若要访问远程计算机上的数据,需要调用 EvtOpenSession 函数来创建远程会话上下文。 调用此函数时,指定要连接到的远程计算机的名称、用于建立连接的用户凭据以及用于对用户进行身份验证的身份验证类型。 若要指定当前用户,请将“域”、“用户”和“密码”成员设置为 NULL。
调用 Windows 事件日志 API 时,会将句柄传递给 EvtOpenSession 函数返回的远程会话上下文。 (若要访问本地计算机上的数据,请传递 NULL 以指定默认会话。) 若要访问远程计算机上的数据,远程计算机必须启用“远程事件日志管理”Windows 防火墙例外;否则,尝试使用会话句柄时,调用将出错,并出现RPC_S_SERVER_UNAVAILABLE。 要连接到的计算机必须运行 Windows Vista 或更高版本。
以下示例演示如何连接到远程计算机。
#include <windows.h>
#include <stdio.h>
#include <winevt.h>
#pragma comment(lib, "wevtapi.lib")
EVT_HANDLE ConnectToRemote(LPWSTR lpwszRemote);
void EnumProviders(EVT_HANDLE hRemote);
void main(void)
{
EVT_HANDLE hRemote = NULL;
LPWSTR pwsComputerName = L"<name of the remote computer goes here>";
// Enumerate the registered providers on the local computer.
wprintf(L"Registered providers on the local computer\n\n");
EnumProviders(hRemote);
hRemote = ConnectToRemote(pwsComputerName);
if (NULL == hRemote)
{
wprintf(L"Failed to connect to remote computer. Error code is %d.\n", GetLastError());
goto cleanup;
}
// Enumerate the registered providers on the remote computer.
// To access a remote computer, the remote computer must enable
// Remote Event Log Management as an exception in the firewall;
// otherwise, the remote call fails with RPC_S_SERVER_UNAVAILABLE.
wprintf(L"\n\nRegistered providers on the remote computer\n\n");
EnumProviders(hRemote);
cleanup:
if (hRemote)
EvtClose(hRemote);
}
// Create a session context for the remote computer. Set the
// Domain, User, and Password member to NULL to specify
// the current user.
EVT_HANDLE ConnectToRemote(LPWSTR lpwszRemote)
{
EVT_HANDLE hRemote = NULL;
EVT_RPC_LOGIN Credentials;
RtlZeroMemory(&Credentials, sizeof(EVT_RPC_LOGIN));
Credentials.Server = lpwszRemote;
Credentials.Domain = NULL;
Credentials.User = NULL;
Credentials.Password = NULL;
Credentials.Flags = EvtRpcLoginAuthNegotiate;
// This call creates a remote session context; it does not actually
// create a connection to the remote computer. The connection to
// the remote computer happens when you use the context.
hRemote = EvtOpenSession(EvtRpcLogin, &Credentials, 0, 0);
SecureZeroMemory(&Credentials, sizeof(EVT_RPC_LOGIN));
return hRemote;
}
// Enumerate the registered providers on the computer.
void EnumProviders(EVT_HANDLE hRemote)
{
EVT_HANDLE hPublishers = NULL;
WCHAR wszPublisherName[255 + 1];
DWORD dwBufferUsed = 0;
DWORD status = ERROR_SUCCESS;
hPublishers = EvtOpenPublisherEnum(hRemote, 0);
if (NULL == hPublishers)
{
wprintf(L"EvtOpenPublisherEnum failed with %d\n", GetLastError());
goto cleanup;
}
while (true)
{
if (EvtNextPublisherId(hPublishers, sizeof(wszPublisherName)/sizeof(WCHAR), wszPublisherName, &dwBufferUsed))
{
wprintf(L"%s\n", wszPublisherName);
}
else
{
status = GetLastError();
if (ERROR_NO_MORE_ITEMS == status)
{
break;
}
else
{
wprintf(L"EvtNextPublisherId failed with 0x%ud\n", GetLastError());
}
}
}
cleanup:
if (hPublishers)
EvtClose(hPublishers);
}