2010-03-29 74 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

相關問題