问题描述
我需要能够在远程计算机上运行RegLoadKey(),并且可能是我的计算机和远程计算机不在同一域中.如果是这样,则下面的代码可以正常工作,并且我可以模拟在计算机上具有管理员特权的用户.否则,如果我们在谈论本地用户,那么根据这次讨论,我发现...
I need to be able to run RegLoadKey() on a remote machine, and it may be that my machine and the remote machine are not in the same domain. If they are, the below code works OK and I can impersonate a user that has admin privileges on the machine. Otherwise, if we're talking about local users, according to this discussion I found...
http://www.eggheadcafe.com/conversation.aspx? messageid = 34224301& threadid = 34224226
...我的计算机上必须有一个具有相同用户名和密码的本地用户.啊.有办法解决吗?
...There has to be a local user on my machine with the same username and password. Ugh. Is there a way around that?
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;
}
推荐答案
这是我一直在使用的,而无需定义本地用户:
Here's what I have been using without having to define a local user:
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
const int LOGON32_PROVIDER_DEFAULT = 0;
bool isSuccess = LogonUser(username, domain, password,
LOGON32_LOGON_NEW_CREDENTIALS,
LOGON32_PROVIDER_DEFAULT, ref token);
之后:
WindowsIdentity newIdentity = new WindowsIdentity(token);
WindowsImpersonationContext impersonatedUser = newIdentity.Impersonate();
虽然我没有重复处理.
另一个观察结果-我不使用LogonUserA,我只是使用LogonUser.
Another observation - I don't use LogonUserA, I simply use LogonUser.
这篇关于使用advapi32.dll:LogonUserA()模拟远程计算机的本地用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!