3
我需要能夠在遠程計算機上運行RegLoadKey(),並且可能是因爲我的計算機和遠程計算機不在同一個域中。如果是,下面的代碼工作正常,我可以模擬在機器上擁有管理員權限的用戶。否則,如果我們談論的本地用戶,根據此討論中,我發現......使用advapi32.dll:LogonUserA()模擬遠程計算機的本地用戶
http://www.eggheadcafe.com/conversation.aspx?messageid=34224301&threadid=34224226
...必須有我的機器上的本地用戶使用相同的用戶名和密碼。啊。有沒有辦法解決這個問題?
using System.Runtime.InteropServices;
using System.Security.Principal;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
public WindowsImpersonationContext WearDrag(string Username, string Password, string DomainOrMachine)
{
WindowsImpersonationContext impersonationContext;
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(Username, DomainOrMachine, Password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return impersonationContext;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return null;
}
好吧,現在它變得很奇怪:它接受任何用戶名和任何密碼,並返回成功! – JCCyC 2009-06-23 21:10:29