C# 执行 cmd 命令
本文关键字:命令 cmd 执行 | 更新日期: 2023-09-27 18:32:59
我试图通过 c# 执行 cmd 命令,一切正常。如何执行包含密码的"runas"cmd,或者至少如何打开cmd提示符以插入密码。我的代码执行效果很好,这是我似乎唯一无法解决的问题。我什至尝试过回声,但它似乎不起作用。
private void btnStart_Click(object sender, EventArgs e)
{
txtResult.Text = string.Empty;
if (txtExecutable.Text.Trim() != string.Empty)
{
StreamReader outputReader = null;
StreamReader errorReader = null;
try
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/C echo " + txtpass.Text + " | runas /user:" + utente.Text + " wmic.exe /node:" + txtExecutable.Text + " ComputerSystem Get UserName && tasklist /s " + txtExecutable.Text + @" /fi ""imagename eq EmpirumRCHost.exe"" && msinfo32.exe ''" + txtParameter.Text;
startInfo.ErrorDialog = false;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
process.StartInfo = startInfo;
process.Start();
bool processStarted = process.Start();
if (processStarted)
{
//Get the output stream
outputReader = process.StandardOutput;
errorReader = process.StandardError;
process.WaitForExit();
//Display the result
string displayText = "Output" + Environment.NewLine + "==============" + Environment.NewLine;
displayText += outputReader.ReadToEnd();
displayText += Environment.NewLine + "Error" + Environment.NewLine + "==============" +
Environment.NewLine;
displayText += errorReader.ReadToEnd();
txtResult.Text = displayText;
}
}
finally
{
if (outputReader != null)
{
outputReader.Close();
}
if (errorReader != null)
{
errorReader.Close();
}
btnStart.Enabled = true;
}
}
}
我需要以在远程 PC 上具有管理权限的域用户身份运行 runas 命令。
可以尝试添加应用程序清单文件,如下所示:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
这就是
你从 C# 运行 shell 命令所要做的全部工作
string strCmdText;
strCmdText= "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);