0

我想使用 ssh 运行命令。
我正在使用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 作为返回码,而不是远程机器上的命令返回的代码。
有人遇到过这个问题,还是我做错了什么?

4

2 回答 2

2

虽然这是一个很晚的回复......这可能对未来的参考有用......

为了从执行的脚本中获取返回码,我们可以使用 RunCommand 本身的返回值。

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

但是,当退出时没有返回码时,这将返回 0。

于 2011-12-16T07:58:58.697 回答
0

If you actually look at the code, getExitStatus is not actually the exit status of the command you ran, it's the exit status of the "Channel" that was just created to run your command. Below is the only place in the entire code base where it's actually set:

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;" is the code in question. And, as you can see it's only set on a Channel open fail. Otherwise, it will be it's default value of -1.

I imagine that Tamir intended to use this a little more extensively, but never did so.

Either way, it was never intended for the purpose you are trying to use it for.

If you are connecting to a linux based machine the only way, with this library, to get the command return code is to end your command call with "echo $?", so you would want to use

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

And then parse the return for that command code at the end. Maybe even prefix it with something easy to parse for, i.e. echo "RETURNCODE"$?

于 2010-06-29T14:13:04.790 回答