We have WCF c# Webservice hosted on IIS(OS win 2012). Want to invoke a powershell command(Want to run DISM commands that need access toe local file system) with Admin privileges.
Steps followed till now:- - Tried impersonating admin user in wcf (C#). - If we print the user after impersonation, impersonation user details will be printed as expected and in this case we have domain administrator. - In the impersonated block, if any process or thread or powershell is executed impersonation is getting lost.
below is the code sinppet of the impersonated block(in the below code, we are trying to create a folder using mkdir).
(Since impersonation from powershell was failing, we tried process after impersonation and in both the cases it is failing).
Process:- //c# impersonate, which is working as expected
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.
}
Powerhell:-
//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();
}
As an alternative approach you could try to psexec
your request:
C:\>psexec -s -u {user} -p {password} cmd /c mkdir c:\test\test123
psexec
will remotely run as the user with full privileges, without using impersonation.
You will need to download put psexec
and put it somewhere available to IIS.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.