我需要将控制器登录到另一台机器上,并在该机器上复制一个文件;我必须使用远程机器上的本地用户。
目前,我正在使用以下代码:
private Impersonate(bool active, string domain, string username, string password, LogonType logonType)
{
if (active)
{
IntPtr handle;
var ok = NativeMethods.LogonUser(username, domain, password, (int)logonType, 0, out handle);
if (!ok)
{
var errorCode = Marshal.GetLastWin32Error();
throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode));
}
_handle = new SafeTokenHandle(handle);
_context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle());
}
}
传递这些参数:
using (Impersonate.LogonUser(true,
".",
"todev1.domain.com\admin",
"Test123_",
LogonType.Interactive))
{
}
还有这个win API:
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
我查看了这个问题和答案 Using advapi32.dll:LogonUserA() to impersonate a remote machine's local user,但所提供的解决方案并没有起作用。
我尝试将多个值作为域、用户等传递给该方法,但我找不到正确的解决方案。我尝试使用NewCredentials,但即使未登录,它也总是返回ok。