How to detect error (as in “Directory not found”, “TNS listener lost contact”, etc) in JSch?

不问归期 提交于 2019-12-08 08:43:17

问题


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

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?

Thanks in advance.


回答1:


The error are usually written to the error output. You can read the error output using 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.


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.




回答2:


If you have a ChannelExec to call a remote command you can use channel.getExitStatus() to get the (non null) numeric exec code in a failure situation (as long as the shell and command you are using are well behaved).



来源:https://stackoverflow.com/questions/37528319/how-to-detect-error-as-in-directory-not-found-tns-listener-lost-contact-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!