2014-04-28 40 views
-1

我需要編寫一個使用PUTTY連接到UNIX服務器,執行命令(例如「ls -la」)的C#代碼,並將腳本結果返回給C#。
我該怎麼做?在C#代碼中啓動PUTTY腳本

我在C#中使用Process.Start來運行PUTTY過程。

+0

http://stackoverflow.com/help/dont- OK – Botonomous

回答

2

你,爲了讓您的膩子處理結果需要的是你的重定向過程stdout (Standard Output)流,並在代碼中使用它:

var processStartInfo = new ProcessStartInfo 
    { 
     FileName = @"C:\PuttyLocation", 
     Arguments = @"-ssh -b abc.txt" 
     RedirectStandardOutput = true, 
     UseShellExecute = false, // You have to set ShellExecute to false 
     ErrorDialog = false 
    }; 

    var process = Process.Start(processStartInfo); 
    if (process == null) 
    { 
     return; 
    } 

    var reader = process.StandardOutput; 
    while (!reader.EndOfStream) 
    { 
     // Read data.. 
    } 
+0

OK。以及如何將參數傳遞給PUTTY?例如,如果我想寫 - putty.exe -ssh -b abc.txt mgroiser @ icsl9932。 – user1616144

+0

在'ProcessStartInfo'中,使用Arguments屬性。編輯我的答案包括這一點。 –

+0

好的。我的Putty位於C:\ tmp \ putty.exe。並且我的abc.txt文件也位於那裏,但是如果我按照您的要求(不指定abc.txt的完整路徑)進行操作,則無法找到該文件。我做了VAR的ProcessStartInfo =新的ProcessStartInfo { 的FileName = @ 「C:\ tmp目錄\ putty.exe」, RedirectStandardOutput = TRUE, UseShellExecute =假,//你要的ShellExecute設置爲false ErrorDialog =假, 參數=「-ssh -m abc.txt mgroiser @ icsl9932」 }; – user1616144