将当前运行EXE的Windows用户替换为其他用户
本文关键字:用户 替换 其他 Windows 运行 EXE | 更新日期: 2023-09-27 17:50:28
假设我构建了一个从网络文件夹读取文件的windows应用程序。网络折叠限制只有一个用户"fooUser"可以访问。该应用程序安装在网络上的几台机器上。
我需要用"fooUser"替换当前用户,以便能够通过代码访问网络文件夹上的文件。
这是一个非常简单的模拟方案,可以让您在一段时间内成为任何人(如果您拥有适当的凭据)。
这个类将为您完成所有繁重的工作....
public class Impersonator : IDisposable
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
private IntPtr token = IntPtr.Zero;
private WindowsImpersonationContext impersonated;
private readonly string _ErrMsg = "";
public bool IsImpersonating
{
get { return (token != IntPtr.Zero) && (impersonated != null); }
}
public string ErrMsg
{
get { return _ErrMsg; }
}
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public Impersonator(string userName, string password, string domain)
{
StopImpersonating();
bool loggedOn = LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token);
if (!loggedOn)
{
_ErrMsg = new System.ComponentModel.Win32Exception().Message;
return;
}
WindowsIdentity identity = new WindowsIdentity(token);
impersonated = identity.Impersonate();
}
private void StopImpersonating()
{
if (impersonated != null)
{
impersonated.Undo();
impersonated = null;
}
if (token != IntPtr.Zero)
{
CloseHandle(token);
token = IntPtr.Zero;
}
}
public void Dispose()
{
StopImpersonating();
}
}
你可以这样使用;
using (Impersonator = new Impersonator(yourName,yourPassword,yourDomain))
{
// Read files from network drives.
// Other activities....
}
将模拟器放置在'using'块中非常重要,或者在完成模拟任务时将其处置,否则系统将继续无限地模拟,从而导致各种问题。
使用runas实用程序:http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/runas.mspx?mfr=true
您可以检查这个问题LogonUser和delegate是否对您有帮助。
您可以直接设置一个映射驱动器到使用'fooUser'凭据的文件夹共享。
虽然如果你有用户的登录名/密码,你可以让你的代码使用模拟。根据我对c#的Windows模拟的回答:
有关模拟代码,请参阅以下两篇代码项目文章:
http://www.codeproject.com/KB/cs/cpimpersonation1.aspx http://www.codeproject.com/KB/cs/zetaimpersonator.aspx和Microsoft KB文章基于:
http://support.microsoft.com/default.aspx?scid=kb; en - us; Q306158