首页 文章

在另一台计算机上模拟本地用户

提问于
浏览
1

我需要将我的控制器登录到另一台机器并在其上复制一个文件;我必须在远程计算机上使用本地用户 .

目前我正在使用此代码:

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());
        }
    }

通过这些args:

using (Impersonate.LogonUser(true,
        ".",
        "todev1.domain.com\admin",
        "Test123_",
        LogonType.Interactive))
    {

    }

这个赢得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);

我检查了这个Q / A Using advapi32.dll:LogonUserA() to impersonate a remote machine's local user但是提供的解决方案无效 .

我试图将多个值作为域,用户等传递给方法,但我找不到严格的解决方案 . 我尝试使用 NewCredentials 但即使没有记录也会返回 .

2 回答

  • 0

    我终于解决了这个问题,而无需将用户添加到将模拟远程计算机的每台计算机上 .

    使用NewCredential是正确的,但使用WINNT50 LogonProvider .

    所以我的模仿方法现在就像:

    private Impersonate(bool active, string domain, string username, string password, LogonType logonType, LogonProvider logonProvider)
            {
                if (active)
                {
                    IntPtr handle;
                    var ok = NativeMethods.LogonUser(username, domain, password, (int)logonType, (int)logonProvider, 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());
                }
            }
    

    然后我使用代码调用Impersonate方法:

    using (Impersonate.LogonUser(true,
        "todev1.domain.com",
        "admin",
        "Test123_",
        LogonType.NewCredentials,
        LogonProvider.WinNT50))
    {
    
    }
    
  • 4

    您可以尝试使用与远程服务器上的本地用户相同的用户名和密码在本地计算机上创建本地用户 .

相关问题