【发布时间】:2011-05-22 16:17:40
【问题描述】:
我正在寻找一种使用 C# 代码启动/停止驻留在远程计算机中的 Windows 服务的方法,并找到了以下代码示例。这对我来说可以。它是使用模拟技术编码的,这显然要求两台机器(比如说 A 和 B)都有一个具有相同 UserName + Password 组合的用户帐户。
int LOGON32_LOGON_INTERACTIVE = 2;
int LOGON32_PROVIDER_DEFAULT = 0;
private bool impersonateValidUser(String userName, String machineName, String passWord)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, machineName, 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 true;
}
}
}
}
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
return false;
}
现在我需要知道以下问题的答案,如果有人能帮助我,我将不胜感激。
对代码的一般解释。
为什么两台机器的用户帐户必须具有相同的用户名+密码组合?
为什么两个用户帐户(Admin 或 Non-Admin)的权限无关?
提前谢谢你。
【问题讨论】:
-
此代码无法编译。您的线路
impersonationContext = tempWindowsIdentity.Impersonate();必须是WindowsImpersonationContext impersonationContext = tempWindowsIdentity.Impersonate();。在if (impersonationContext != null) { ... }中,您可以作为其他帐户进行工作。 -
更好的方法是让这个函数返回 WIC,这样您就可以在别处工作,并在完成后调用另一个函数来关闭您的令牌句柄。看看我在这里做了什么:stackoverflow.com/questions/1335065/…
标签: c# windows windows-services impersonation remote-access