我创建了一个进程处理程序,它启动两种类型的进程: 一个使用管理员用户名和密码提升的 另一个无需输入任何用户名和密码即可正常运行的。
我正在努力弄清楚如何从提升的过程中获得输出。启动进程的应用程序不需要管理员凭据即可运行,管理员凭据在单独的加密 xml 文件中输入,应用程序在脚本和其他需要管理员凭据的地方使用该文件。
由于应用程序是由普通用户运行的,因此访问应用程序已启动的提升进程似乎是不可能的。我可以启动一个进程,我可以轻松地检查它是否完成了它应该做的事情,但我无法将它的操作读取到字符串或日志中。
public bool CreateProcessWithAdminRights(string filePath, string commandlineArgument, bool log)
{
if (!string.IsNullOrEmpty(filePath) && !string.IsNullOrEmpty(commandlineArgument) && _user.UserDataExsists())
{
var securePassword = GetSecureString(_user.Password);
ToolsProvider.Logger.Debug("Creating process with the following filepath: {0} and commandline argument: {1}", filePath, commandlineArgument.Replace(_user.Password, "<REPLACED>"));
ToolsProvider.Logger.Info("Creating Process with admin rights for {0} against {1}", _user.Name );
_proc = new Process
{
StartInfo =
{
FileName = @filePath,
Arguments = commandlineArgument,
ErrorDialog = false,
RedirectStandardInput = false,
RedirectStandardOutput = _log,
RedirectStandardError = _log,
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
UserName = _user.Name,
Password = securePassword,
Domain = _user.Domain
}
};
_proc.ErrorDataReceived += ErrorDataReceived;
_proc.OutputDataReceived += OutputDataReceived;
return true;
}
return false;
}
进程开始使用:
private bool StartProcess()
{
if (_proc != null)
{
try
{
_proc.Start();
_proc.BeginErrorReadLine();
_proc.BeginOutputReadLine();
_proc.WaitForExit();
_proc.CancelOutputRead();
_proc.CancelErrorRead();
if (_standardOutput.Length > 2)
{
// use writeline, the builder itself will add the DEBUG / info tag
ToolsProvider.Logger.WriteLine(_standardOutput.ToString());
}
if (_errorBuilder.Length > 2)
{
// use writeline, the builder itself will add the DEBUG / info tag
ToolsProvider.Logger.WriteLine(_errorBuilder.ToString());
}
return true;
}
catch (Win32Exception ex)
{
ToolsProvider.Logger.Error(
"Missing file while trying to run an action: " + _proc.StartInfo.FileName, ex.Message);
}
}
ToolsProvider.Logger.Error("");
return false;
}
我也尝试过使用 Impersonator 类启动进程,无论是否向进程添加管理员凭据。模拟类什么也没做,只是告诉我我没有访问权限,尽管我正在模拟管理员......
我从这里得到了 Impersonator 类:
http://freshclickmedia.co.uk/2008/11/programmatic-impersonation-in-c/
那么,如何在未提升的进程中从提升的进程中获取标准和错误输出?
最佳答案
你只能通过入侵系统和/或利用一些错误和/或编写一些内核级代码(即驱动程序)来规避这些安全措施......
想想这种可能性意味着什么——提升将变得毫无意义,因为系统中总是有一些可以通过这种方式操纵的提升进程……所以答案是否定的……
您应该能够做的是将输出重定向到一个文件(例如 > C:\MyLog.txt
),然后读取该文件...
考虑一种不需要这种访问权限的不同设计...
关于c# - 从提升的子进程中获取错误和标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7902649/