[英]To run cmd as administrator along with command?
这是我的代码:
try
{
ProcessStartInfo procStartInfo = new ProcessStartInfo(
"cmd.exe",
"/c " + command);
procStartInfo.UseShellExecute = true;
procStartInfo.CreateNoWindow = true;
procStartInfo.Verb = "runas";
procStartInfo.Arguments = "/env /user:" + "Administrator" + " cmd" + command;
///command contains the command to be executed in cmd
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
我想保留
procStartInfo.UseShellExecute = true
procStartInfo.RedirectStandardInput = false;
是否可以在不使用process.standardinput
情况下执行命令? 我尝试执行命令我已经传入参数,但命令没有执行。
正如@mtijn所说,你有很多事情要做,以后你也会压倒一切。 你还需要确保你正确地逃避了事情。
假设您要运行以下提升的命令:
dir c:\
首先,如果您只是通过Process.Start()
运行此命令,则会立即打开并关闭一个窗口,因为没有任何东西可以保持窗口打开。 它处理命令并退出。 要保持窗口打开,我们可以将命令包装在单独的命令窗口中,并使用/K
开关使其保持运行:
cmd /K "dir c:\"
要运行该命令,我们可以像使用runas.exe
一样使用runas.exe
,除了我们需要更多地转义。 根据帮助文档( runas /?
),我们传递给runas
的命令中的任何引号都需要使用反斜杠进行转义。 不幸的是,使用上面的命令执行此操作会给我们一个双重反斜杠,这会使cmd解析器混淆,因此也需要进行转义。 所以上面的命令将最终成为:
cmd /K \"dir c:\\\"
最后,使用您提供的语法,我们可以将所有内容包装到runas
命令中,并将上面的命令括在另一组引号中:
runas /env /user:Administrator "cmd /K \"dir c:\\\""
从命令提示符运行上面的命令,以确保它按预期方式工作。
鉴于所有这些,最终代码变得更容易组装:
//Assuming that we want to run the following command:
//dir c:\
//The command that we want to run
string subCommand = @"dir";
//The arguments to the command that we want to run
string subCommandArgs = @"c:\";
//I am wrapping everything in a CMD /K command so that I can see the output and so that it stays up after executing
//Note: arguments in the sub command need to have their backslashes escaped which is taken care of below
string subCommandFinal = @"cmd /K \""" + subCommand.Replace(@"\", @"\\") + " " + subCommandArgs.Replace(@"\", @"\\") + @"\""";
//Run the runas command directly
ProcessStartInfo procStartInfo = new ProcessStartInfo("runas.exe");
procStartInfo.UseShellExecute = true;
procStartInfo.CreateNoWindow = true;
//Create our arguments
string finalArgs = @"/env /user:Administrator """ + subCommandFinal + @"""";
procStartInfo.Arguments = finalArgs;
//command contains the command to be executed in cmd
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo = procStartInfo;
proc.Start();
}
为什么要用参数初始化进程对象,然后再覆盖那些参数? 和btw:你设置参数的最后一位你将'命令'连接到'cmd',这没有多大意义,可能是它失败的地方(看起来你错过了一个空格)。
此外,您当前正在使用标准命令行,您可能希望使用runas工具 。 你也可以从命令行调用runas。
另外,为什么要从命令行运行'command'? 为什么不直接从Process.Start启动它,然后提供管理员权限? 这里有点伪代码:
Process p = Process.Start(new ProcessStartInfo()
{
FileName = <your executable>,
Arguments = <any arguments>,
UserName = "Administrator",
Password = <password>,
UseShellExecute = false,
WorkingDirectory = <directory of your executable>
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.