2014-12-21 29 views
1

我想用C#在PuTTY中運行Unix命令。我有下面的代碼。但代碼不起作用。我無法打開PuTTY。在C#中使用PuTTY運行Unix命令

static void Main(string[] args) 
{ 
    Process cmd = new Process(); 
    cmd.StartInfo.FileName = @"C:\Windows\System32\cmd"; 
    cmd.StartInfo.UseShellExecute = false; 
    cmd.StartInfo.RedirectStandardInput = false; 
    cmd.StartInfo.RedirectStandardOutput = true; 
    cmd.Start(); 
    cmd.StartInfo.Arguments = "C:\Users\win7\Desktop\putty.exe -ssh [email protected] 22 -pw mahi"; 
} 
+0

你已經走了有點不對勁有隊友。看看http://stackoverflow.com/questions/6147203/automating-running-command-on-linux-from-windows-using-putty –

回答

2

這應該工作:

static void Main(string[] args) 
    { 
     ProcessStartInfo cmd = new ProcessStartInfo(); 
     cmd.FileName = @"C:\Users\win7\Desktop\putty.exe"; 
     cmd.UseShellExecute = false; 
     cmd.RedirectStandardInput = false; 
     cmd.RedirectStandardOutput = true; 
     cmd.Arguments = "-ssh [email protected] 22 -pw mahi"; 
     using (Process process = Process.Start(cmd)) 
     { 
      process.WaitForExit(); 
     } 
    } 
+0

儘管代碼確實執行了PuTTY,但它是如何讓您執行命令的? –

+1

如果你想運行命令,我建議使用一個SSH庫,比如[SSH.NET](http://sshnet.codeplex.com/)和使用putty。 –

6
  • putty.exe是一個GUI應用程序。它旨在交互式使用,而不是自動化。嘗試重定向其標準輸出沒有意義,因爲它沒有使用它。

  • 對於自動化,請使用PuTTY包中的另一個工具plink.exe
    這是一個控制檯應用程序,因此您可以重定向其標準輸出/輸入。

  • 試圖通過cmd.exe間接執行應用程序沒有意義。直接執行。

  • 您還需要重定向標準輸入,以便能夠將命令提供給Plink。

  • 您必須在致電.Start()之前提供參數。

  • 您也可能想重定向錯誤輸出(RedirectStandardError)。雖然請注意,您需要並行讀取輸出和錯誤輸出,但代碼複雜。


static void Main(string[] args) 
{ 
    Process cmd = new Process(); 
    cmd.StartInfo.FileName = @"C:\Program Files (x86)\PuTTY\plink.exe"; 
    cmd.StartInfo.UseShellExecute = false; 
    cmd.StartInfo.RedirectStandardInput = true; 
    cmd.StartInfo.RedirectStandardOutput = true; 
    cmd.StartInfo.Arguments = "-ssh [email protected] 22 -pw mahi"; 
    cmd.Start(); 
    cmd.StandardInput.WriteLine("./myscript.sh"); 
    cmd.StandardInput.WriteLine("exit"); 
    string output = cmd.StandardOutput.ReadToEnd(); 
} 
+0

@MartinPrikrylI有一個問題,如果我在Unix上運行這個命令'execute_unix_program('shell','sh $ ORF_SRC/anly_load_int.sh');'我將如何使用您的示例執行此操作?我想要做的就是從我的Windows應用程序exexute這個命令..我不知道使用'plink.exe'會工作..謝謝 – MethodMan

+0

你只需使用'sh $ ORF_SRC/anly_load_int.sh'而不是'。/myscript.sh'。 –

+0

所以我可以做以下'cmd.StandardInput.WriteLine(「./$ ORF_SRC/anly_load_int.sh」);'是正確的..?如果是這樣,我會嘗試它..感謝快速回應 – MethodMan