在Winform C中输入参数和cmd.exe的密码#

问题描述:

我必须建立一个使用cmd.exe的ssh连接。我在一个winform应用程序中使用一个按钮来完成这个过程。在我通过ssh连接的命令后,cmd.exe提示输入密码。除了传递ssh -p [email protected]命令(用于建立连接)之外,我如何传递密码作为参数?我必须运行cmd.exe作为后台进程。请帮忙。谢谢。在Winform C中输入参数和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 [email protected]"); //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 {} 
    } 
+0

[?ProcessStartInfo.RedirectStandardInput(http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardinput(V = vs.110).aspx)请显示您的代码,以便我们可以给出适合的答案。 – 2014-10-18 03:37:06

+0

添加了我的代码。问题是我尝试使用的代码无法传递密码。 – znb 2014-10-20 07:33:34

您需要Startprocess

在此之前,您需要将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 [email protected]"); //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 
      } 
     } 
+0

此代码也不提供输出。问题是我尝试使用的代码无法通过密码。感谢你的回答 – znb 2014-10-20 07:32:55