以编程方式提升进程权限?
-
02-07-2019 - |
题
我正在尝试使用InstallUtil.exe安装服务,但是通过 Process.Start
调用。这是代码:
ProcessStartInfo startInfo = new ProcessStartInfo (m_strInstallUtil, strExePath);
System.Diagnostics.Process.Start (startInfo);
其中 m_strInstallUtil
是完全限定的路径,并且exe为“InstallUtil.exe”。和 strExePath
是我服务的完全限定路径/名称。
从提升的命令提示符运行命令行语法有效;从我的应用程序运行(使用上面的代码)没有。我假设我正在处理一些进程提升问题,那么我如何在高架状态下运行我的进程?我需要查看 ShellExecute
吗?
这一切都在Windows Vista上。我正在VS2008调试器中运行升级到管理员权限的进程。
我也试过设置 startInfo.Verb =" runas";
但似乎没有解决问题。
解决方案
您可以通过将startInfo对象的Verb属性设置为'runas'来指示应使用提升的权限启动新进程,如下所示:
startInfo.Verb = "runas";
这将导致Windows的行为就好像已使用“以管理员身份运行”从资源管理器启动进程一样菜单命令。
这确实意味着UAC提示将出现并且需要得到用户的确认:如果这是不合需要的(例如因为它会在漫长的过程中发生),您将需要运行整个创建和嵌入应用程序清单(UAC)的权限提升的主机进程要求'highestAvailable'执行级别:这将导致UAC提示在应用程序启动后立即显示,并导致所有子进程以提升的权限运行而无需其他提示。
编辑:我看到你刚编辑了你的问题,说明“runas”不适合你。这真的很奇怪,因为它应该(在我的几个生产应用程序中也适用)。但是,通过嵌入清单要求父进程以提升的权限运行应该绝对可行。
其他提示
此代码将上述所有内容放在一起,并使用admin privs:
重新启动当前的wpf应用程序if (IsAdministrator() == false)
{
// Restart program and run as admin
var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
startInfo.Verb = "runas";
System.Diagnostics.Process.Start(startInfo);
Application.Current.Shutdown();
return;
}
private static bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
// To run as admin, alter exe manifest file after building.
// Or create shortcut with "as admin" checked.
// Or ShellExecute(C# Process.Start) can elevate - use verb "runas".
// Or an elevate vbs script can launch programs as admin.
// (does not work: "runas /user:admin" from cmd-line prompts for admin pass)
更新:首选应用清单方式:
右键单击visual studio中的项目,添加新的应用程序清单文件,更改文件,以便设置requireAdministrator,如上所示。
原始方式存在问题:如果将重启代码放在app.xaml.cs OnStartup中,即使调用了Shutdown,它仍可能会短暂启动主窗口。如果没有运行app.xaml.cs init,我的主窗口会爆炸,在某些竞争条件下它会执行此操作。
根据文章 Chris Corio:教你的应用程序使用Windows Vista用户帐户控制,MSDN杂志,2007年1月 ,只有 ShellExecute
检查嵌入式清单并在需要时提示用户提升,而 CreateProcess
和其他API则不提示。希望它有所帮助。
参见:与.chm相同的文章。
[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]
这将在没有UAC的情况下完成 - 无需启动新流程。如果正在运行的用户是我的案例的管理员组的成员。
您应该使用Impersonation来提升状态。
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();
完成后不要忘记撤消模拟的上下文。