Start a process as user from an process running as admin

放肆的年华 提交于 2019-12-10 13:57:35

问题


I want to start another program which runs as user from a program running as administrator.

The problem is that the second program needs to use outlook, which is not possible if the program runs as admin. The main program needs to run as admin.

I did already come up with this two solutions:

Process.Start("cmd.exe", @"/C runas.exe /savecred /user:" + Environment.UserDomainName + "\\" + Environment.UserName + " " + "\"SomeProgram.exe" + "\"");

or

Process.Start("explorer.exe", "SomeProgram.exe");

But i have a problem with both solutions. The first one asks the user for the password (only the first time after windows was restarted). The second one probalby won`t work in the future, because as far as i found out it is considered as a bug and probably fixed with an future update.

So I would like to know is there any other solution, where the user does not need to enter his password?

This seems to work for me:

Process.Start("cmd.exe", @"/C runas.exe /TrustLevel:0x20000  " + "\"SomeProgram.exe" + "\"");

回答1:


Process class has StartInfo property that is an instance of ProcessStartInfo class. This class exposes UserName, Domain and Password members to specify the user you want to run the process.

Process myProcess = new Process();
myProcess.StartInfo.FileName = fileName;
myProcess.StartInfo.UserName = userName;
myProcess.StartInfo.Domain = domain;
myProcess.StartInfo.Password = password;
myProcess.Start();



回答2:


I was having the same issue and was not able to get the current logged user. NB: querying wmi is not a solution as many users may be logged in at that time so my solution is to do the reverse. Launch my app as current user and if the current user is not admin, I request to run as admin.

if (IsAdministrator())
{
    // run whatever you want as elevated user
}
else
{
    //launch the same app as admin
    ExecuteAsAdmin(PATHH_TO_THE_SAME_APP.EXE);
    //execute whatever you want as current user.
}



public static void ExecuteAsAdmin(string fileName)
{
    Process proc = new Process();
    proc.StartInfo.FileName = fileName;
    proc.StartInfo.UseShellExecute = true;
    proc.StartInfo.Verb = "runas";

    proc.Start();
    proc.WaitForExit();
}

public static bool IsAdministrator()
{
    var identity = WindowsIdentity.GetCurrent();
    var principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}


来源:https://stackoverflow.com/questions/31646768/start-a-process-as-user-from-an-process-running-as-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!