在cmd.exe中以winform C#输入参数和密码
本文关键字:输入 参数 密码 winform cmd exe 中以 | 更新日期: 2023-09-27 18:26:53
我必须使用cmd.exe建立ssh
连接。我使用winform应用程序中的按钮来完成此过程。在我为ssh
连接传递命令后,cmd.exe
会提示输入密码。除了传递ssh -p root@localhost
命令(用于建立连接)之外,我如何传递密码作为参数?我必须运行cmd.exe
作为后台进程。请帮忙。非常感谢。
我是c#的新手,我尝试过的代码之一是:
private void button2_Click(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
using (StreamWriter sw = process.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("/c ssh -p 2022 root@localhost"); //first comand i need to enter
sw.WriteLine("/c alpine");//command to be typed as password in response to 1st cmd's output
sw.WriteLine("/c mount.sh");//command to be typed nest in response to 2nd cmd's next output
}
}
}
catch {}
}
您需要Start
您的process
。
在此之前,您需要将startinfo
分配给您的process
。
此外,如果不想打开窗口,则应使用CreateNoWindow
,而不是将WindowStyle
设置为Hidden
。
我把你的代码改成这样:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
using (StreamWriter sw = process.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("/c ssh -p 2022 root@localhost"); //first comand i need to enter
sw.WriteLine("/c alpine");//command to be typed as password in response to 1st cmd's output
sw.WriteLine("/c mount.sh");//command to be typed nest in response to 2nd cmd's next output
}
}