我有一个单击按钮来执行命令。该命令可能会提示一些标准输入,我需要响应该输入,问题是程序运行的方式可能每天都不同,所以我需要解释标准输出并相应地重定向标准输入。
我有这段简单的代码,它逐行读取标准输出,当它看到密码提示时,它会发送标准输入,但是程序只是挂起,因为它从来没有看到密码提示,但是当我运行批处理文件有密码提示。
这是我为执行此测试而调用的批处理文件:
@echo off
echo This is a test of a prompt
echo At the prompt, Enter a response
set /P p1=Enter the Password:
echo you entered "%p1%"
这是从命令行运行时该批处理文件的输出:
C:\Projects\SPP\MOSSTester\SPPTester\bin\Debug>test4.bat
This is a test of a prompt
At the prompt, Enter a response
Enter the Password: Test1
you entered "Test1"
这是我用来调用挂起的批处理文件的 C# 片段:
var proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "/c test4.bat";
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
//read the standard output and look for prompt for password
StreamReader sr = proc.StandardOutput;
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
Debug.WriteLine(line);
if (line.Contains("Password"))
{
Debug.WriteLine("Password Prompt Found, Entering Password");
proc.StandardInput.WriteLine("thepassword");
}
}
sr.Close();
proc.WaitForExit();
这是我看到的调试标准输出,注意我从来没有看到密码提示,这是为什么?它只是挂起?
This is a test of a prompt
At the prompt, Enter a response
有没有办法可以观察标准输出以进行提示并做出相应的反应?