我们在 IIS(OS win 2012)上托管了 WCF c# Webservice。想要以管理员权限调用 powershell 命令(想要运行需要访问本地文件系统的 DISM 命令)。
到现在为止的步骤:- - 尝试在 wcf (C#) 中模拟管理员用户。- 如果我们在模拟后打印用户,模拟用户详细信息将按预期打印,在这种情况下,我们有域管理员。- 在模拟块中,如果执行任何进程或线程或 powershell,模拟就会丢失。
下面是模拟块的代码片段(在下面的代码中,我们正在尝试使用 mkdir 创建一个文件夹)。
(由于从 powershell 模拟失败,我们在模拟后尝试了过程,并且在这两种情况下都失败了)。
Process:- //c# impersonate,按预期工作
Impersonate.ImpersonateUser("mydomain", "administrator", "mypasswd");
{
// Printed windows idenitty and impersonated user details are printed
here.
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.UseShellExecute = false;
processStartInfo.UserName = "administrator";
processStartInfo.Domain = "mydomain";
processStartInfo.Password = secureString;
Process process = Process.Start(processStartInfo);
process.StandardInput.WriteLine(@"mkdir c:\test\test123"); //
'mydomain\administrator' has access to test folder.
process.StandardInput.Close();
string output = process.StandardOutput.ReadToEnd();
// folder is not getting and created(no output), not getting any
exception.
}
强力地狱:-
//After c# impersonation, tried the below c#.
WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
WindowsImpersonationContext ctx = null;
try
{
ctx = winId.Impersonate();
Runspace myRunSpace = RunspaceFactory.CreateRunspace();
myRunSpace.Open();
Command cmd1 = new Command("get-process", true);
pipeline.Commands.Add(cmd1);
Pipeline pipeline =
myRunSpace.CreatePipeline(“WindowsIdentity]::GetCurrent().Name”);
System.Collections.ObjectModel.Collection<PSObject> objectRetVal =
pipeline.Invoke();
myRunSpace.Close();
ctx.Undo();
}