【问题标题】:What is the reason to get exit status value -1 in JSch在 JSch 中获得退出状态值 -1 的原因是什么
【发布时间】:2014-02-12 08:24:44
【问题描述】:

我正在尝试使用 JSch (SSH) API 从 Java 在远程 Linux 机器上运行命令。 exitStatus 的值为 -1

int exitStatus = channelExec.getExitStatus()

得到负值的可能原因是什么?

【问题讨论】:

标签: java ssh jsch


【解决方案1】:

channelName.getExitStatus()

它将检索与您的频道对应的远程命令的退出状态。如果命令尚未终止(或该频道类型没有命令),它将返回状态为-1

更多信息请到jsch documentation

【讨论】:

    【解决方案2】:

    API Description

    这是我的代码。它工作正常。

    public static Result sendCommand(String ip, Integer port, String userName, String password, String cmd) {
        Session session = null;
        ChannelExec channel = null;
        Result result = null;
        try {
            JSch jsch = new JSch();
            JSch.setConfig("StrictHostKeyChecking", "no");
    
            session = jsch.getSession(userName, ip, port);
            session.setPassword(password);
            session.connect();   
    
            channel = (ChannelExec)session.openChannel("exec");
            InputStream in = channel.getInputStream();
            channel.setErrStream(System.err);
            channel.setCommand(cmd);
            channel.connect();
    
            StringBuilder message = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                message.append(line).append("\n");
            }
            channel.disconnect();
            while (!channel.isClosed()) {
    
            }
            result = new Result(channel.getExitStatus(),message.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                try {
                    session.disconnect();
                } catch (Exception e) {
    
                }
            }
        }
        return result;
    }
    

    【讨论】:

    • channel.setErrStream(System.err);真的帮我找出了为什么我的输入流总是 0...
    【解决方案3】:

    在 getExitStatus() 上注明 the documentation

    退出状态将为-1,直到通道关闭。

    【讨论】:

      【解决方案4】:

      '-1'表示尚未从远程sshd收到退出状态码。

      【讨论】:

      • 当我没有机会等待输出传输时,它确实返回了-1。如果你等待结果,它可能会改变
      猜你喜欢
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 2011-08-19
      • 2020-11-16
      • 2011-01-11
      • 2019-04-03
      • 2021-01-17
      • 1970-01-01
      相关资源
      最近更新 更多