2014-10-18 49 views
0

我必須建立一個使用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

回答

0

您需要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