如何在JSch中检测错误(如“未找到目录”,“TNS监听器失去联系”等)? [英] How to detect error (as in "Directory not found", "TNS listener lost contact", etc) in JSch?

查看:533
本文介绍了如何在JSch中检测错误(如“未找到目录”,“TNS监听器失去联系”等)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在使用JSch触发任何命令时收到错误消息。

I need to get error message while firing any command using JSch.

目前我使用下面的代码来获取 tail的输出命令,但如果文件不存在,我应该把错误作为输出(我没有得到)。

Currently I am using below code to get output of tail command, but if the file does not exist, I should get the error as output (which I am not getting).

public String getOutput() {
    LOGGER.debug("[getOutput]");
    StringBuffer output = new StringBuffer();
    InputStream in = null;
    if (channel != null && channel.isConnected()) {
        try {
            in = channel.getInputStream();

            byte[] tmp = new byte[1024];
            while (true) {
                LOGGER.debug("[getOutput] in while");
                while (in.available() > 0) {
                    LOGGER.debug(in.available());
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0)
                        break;
                    output.append(new String(tmp, 0, i));
                }
                if (channel.isClosed()) {
                    LOGGER.debug("[getOutput] Channel is closed, so breaking while loop");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            channel.disconnect();
        }
    } else {
        System.out.println("Channel is disconnected");
    }

    return output.toString();
}

我有什么方法可以收到错误消息吗?

Is there any way i could get the error message too?

提前致谢。

推荐答案

错误通常会写入错误输出。您可以使用 getErrStream 读取错误输出。

The error are usually written to the error output. You can read the error output using getErrStream.

请注意,您需要读取标准输出( getInputStream )并行错误输出,不按顺序输出。我的意思是你不能只是克隆你的循环,你有 getInputStream ,对于 getErrStream 。你需要有一个循环,从两者中读取(读取一个可用的内容,读取第二个中可用的内容,等待新数据并重复)

Note that you need to read the standard output (getInputStream) and the error output in parallel, not in sequence. I mean that you cannot just clone your while loop, you have for getInputStream, for getErrStream. You need to have one loop, reading from both (read what's available in one, read what's available in the second, wait for new data and repeat)

当你第一次阅读时一个然后另一个,如果后一个输出很大,它的输出缓冲区变满,命令停止,永远不会完成。因此,如果您一直等待第一个输出关闭,您就会与服务器发生死锁。

When you read first one and then the other, if the latter output is large, its output buffer gets full, the command stops, never finishing. So if you keep waiting for the first output to close, you deadlock with the server.

请注意 Auth failed不是命令输出的错误。这是JSch库抛出的异常。所以这与你的代码无关。

Note that the "Auth failed" is not an error outputted by a command. It's an exception thrown by the JSch library. So it's irrelevant to your code.

这篇关于如何在JSch中检测错误(如“未找到目录”,“TNS监听器失去联系”等)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆