2010-03-29 77 views
13

This .NET API工作正常,如果我试图打开与我在同一域中的计算机上的注册表(并且我的登录用户在目标计算机上拥有管理权限)。如何将凭证传递给机器,以便我可以使用Microsoft.Win32.RegistryKey.OpenRemoteBaseKey()?

如果它是具有不同本地管理用户(我确实拥有密码)的域外机器,则会变得棘手。

在尝试调用OpenRemoteBaseKey()之前,我尝试使用WNetUseConnection()(它在过去的情况下很好地解决了我想要读取远程磁盘文件的情况),但没有骰子 - 我得到一个拒绝访问。

很明显,我必须通过其他方式凭证,但怎么办?

回答

32

我已经成功地用于访问文件的计算机上为下面的代码:

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

正如你可能会看到, “撤消()”将使您不再以该用户的身份登录。所以在你完成之前不要使用它。但不要忘记使用它!

+2

+1这真的是唯一的方法。 – Nate 2010-03-29 22:00:59

+0

我是否可以长时间保持“标记”变量,然后在使用相同标记的不同点处使用“使用/撤消()”块?“ – JCCyC 2010-03-29 22:19:31

+0

我这样认为是实际登录的模拟。我使用的是一个返回WindowsImpersonationContext的“GetImpersonation()”,如上所示 – 2010-03-29 22:22:27

相关问题