代码之家  ›  专栏  ›  技术社区  ›  JCCyC

如何将凭据传递给计算机以便在其上使用Microsoft.win32.RegistryKey.OpenRemoteBaseKey()?

  •  13
  • JCCyC  · 技术社区  · 16 年前

    This .NET API 如果我试图在与我位于同一域的计算机上打开注册表(并且我的登录用户对目标计算机具有管理员权限),则可以正常工作。

    如果它是一个域外的机器,并且有一个不同的本地管理用户(我确实有这个用户的密码),那就很难了。

    我试着用 WNetUseConnection() 在调用openremotebasekey()之前(在过去我希望读取远程磁盘文件的情况下,这对我很有用),但是没有骰子——我得到一个拒绝访问的异常。

    显然,我必须通过其他方式传递证书,但如何传递?

    1 回复  |  直到 15 年前
        1
  •  32
  •   Oskar Kjellin    16 年前

    我成功地用来访问计算机上的文件的代码如下:

        #region imports 
            [DllImport("advapi32.dll", SetLastError = true)] 
            private static extern bool LogonUser(string 
            lpszUsername, string lpszDomain, string lpszPassword, 
            int dwLogonType, int dwLogonProvider, ref 
    IntPtr phToken); 
    
    
            [DllImport("kernel32.dll", CharSet = CharSet.Auto, 
            SetLastError = true)] 
            private static extern bool CloseHandle(IntPtr handle 
            ); 
    
            [DllImport("advapi32.dll", CharSet = CharSet.Auto, 
            SetLastError = true)] 
            public extern static bool DuplicateToken(IntPtr 
            existingTokenHandle, 
            int SECURITY_IMPERSONATION_LEVEL, ref IntPtr 
            duplicateTokenHandle); 
            #endregion 
            #region logon consts 
            // logon types 
            const int LOGON32_LOGON_INTERACTIVE = 2; 
            const int LOGON32_LOGON_NETWORK = 3; 
            const int LOGON32_LOGON_NEW_CREDENTIALS = 9; 
    
            // logon providers 
            const int LOGON32_PROVIDER_DEFAULT = 0; 
            const int LOGON32_PROVIDER_WINNT50 = 3; 
            const int LOGON32_PROVIDER_WINNT40 = 2; 
            const int LOGON32_PROVIDER_WINNT35 = 1; 
            #endregion 
    

    然后,对于部分签名,只需使用:

            IntPtr token = IntPtr.Zero; 
    
            bool isSuccess = LogonUser("username", "domain", "password", 
            LOGON32_LOGON_NEW_CREDENTIALS, 
            LOGON32_PROVIDER_DEFAULT, ref token); 
            using (WindowsImpersonationContext person = new WindowsIdentity(token).Impersonate()) 
            { 
            //do your thing 
             person.Undo(); 
            } 
    

    如您所见,“undo()”将使您不再作为该用户登录。所以在完成之前不要使用它。但别忘了用它!

    推荐文章