2010-05-07 134 views
0

我想用ssh運行一個命令。
我使用SharpSSH library,如下例:運行一個不產生輸出的命令,用SharpSSH

using System; 
using Tamir.SharpSsh; 

class Program { 
    static void Main(string[] args) { 
     string hostName = "host.foo.com"; 
     string userName = "user"; 
     string privateKeyFile = @"C:\privatekey.private"; 
     string privateKeyPassword = "xxx"; 

     SshExec sshExec = new SshExec(hostName, userName); 
     sshExec.AddIdentityFile(privateKeyFile, privateKeyPassword); 
     sshExec.Connect(); 
     string command = string.Join(" ", args); 
     Console.WriteLine("command = {0}", command); 
     string output = sshExec.RunCommand(command); 

     int code = sshExec.ChannelExec.getExitStatus(); 
     sshExec.Close(); 
     Console.WriteLine("code = {0}", code); 
     Console.WriteLine("output = {0}", output); 
    } 
} 

我的問題是,當我運行命令不產生輸出,我得-1作爲返回代碼,而不是由命令返回上的代碼遠程機器。
有人遇到過這個問題,或者我做錯了什麼?

+0

您是否嘗試過使用RunCommand的重載並忽略stdOut和stdErr並讀取退出的代碼?我想這似乎沒有太大區別。 – kamranicus 2011-01-20 20:50:56

回答

0

如果您真的查看代碼,getExitStatus實際上並不是您運行的命令的退出狀態,而是剛創建用於運行命令的「通道」的退出狀態。以下是整個代碼庫中實際設置的唯一位置:

case SSH_MSG_CHANNEL_OPEN_FAILURE: 
          buf.getInt(); 
          buf.getShort(); 
          i=buf.getInt(); 
          channel=Channel.getChannel(i, this); 
          if(channel==null) 
          { 
           //break; 
          } 
          int reason_code=buf.getInt(); 
          //foo=buf.getString(); // additional textual information 
          //foo=buf.getString(); // language tag 
          channel.exitstatus=reason_code; 
          channel._close=true; 
          channel._eof_remote=true; 
          channel.setRecipient(0); 
          break; 

「channel.exitstatus = reason_code;」是有問題的代碼。而且,正如你所看到的,它只是設置在頻道打開失敗。否則,它將是默認值-1。

我想坦米爾打算使用這個更廣泛一點,但從來沒有這樣做。

無論哪種方式,它從來沒有打算用於你試圖使用它的目的。

如果要連接到基於Linux機器的唯一途徑,與此庫,以獲得命令的返回碼是結束你的命令調用「回聲$?」,所以你可能需要使用

sshExec.RunCommand(command + ";echo $?"); 

然後在最後解析該命令代碼的返回值。甚至可以用易於解析的東西加前綴,即echo「RETURNCODE」$?

+0

感謝您的回答和'echo $?'建議,但實際上,如果我運行的命令產生輸出,那麼退出狀態**是**命令返回代碼... – 2010-06-29 20:45:49

2

雖然這是一個非常晚的答覆......這可能是futhure引用有用...

對於來自執行腳本獲取返回代碼,就可以中使用RunCommand本身的返回值。

int returnCode = exec.RunCommand(strScript2, ref stdOut, ref stdError); 

但是,當退出時沒有返回碼時,這將返回0。

相關問題